javapython冒泡排序纯代码分享排序分享

    科技2025-08-29  10

    Java交换排序--冒泡排序 class sort{ int temp;//临时变量 public void swap(int[] a,int i,int j) {//两个数之间交换 temp=a[i]; a[i]=a[j]; a[j]=temp; } public void maopao(int[] a) {//冒泡排序 for(int i=0;i<a.length-1;i++) {//进行n次交换排序 for(int j=a.length-1;j>i;j--) { if(a[j]<a[j-1]) {//进行比较交换 this.swap(a, j, j-1); } } } } } public class BubbleSort { public static void main(String[] args) { int[] a= {55,44,85,16,12,17,99,65}; System.out.println("冒泡排序之前的数组顺序"); for(int i=0;i<=a.length-1;i++) { System.out.print(a[i]+" "); } System.out.println(); sort bulbbleSort=new sort(); bulbbleSort.maopao(a); System.out.println("冒泡排序之后的数组顺序"); for(int i=0;i<=a.length-1;i++) { System.out.print(a[i]+" "); } } } 冒泡排序改进版 class sort{ int temp;//临时变量 boolean flag;//判断是否交换了 public void swap(int[] a,int i,int j) {//两个数之间交换 temp=a[i]; a[i]=a[j]; a[j]=temp; } public void maopao(int[] a) {//冒泡排序 for(int i=0;i<=a.length-1;i++) {//进行n次交换排序 flag=false; for(int j=a.length-1;j>i;j--) { if(a[j]<a[j-1]) {//进行比较交换 this.swap(a, j, j-1); flag=true; } } if(!flag) break; } } } public class BubbleSort { public static void main(String[] args) { int[] a= {55,44,85,16,12,17,99,65}; System.out.println("冒泡排序之前的数组顺序"); for(int i=0;i<=a.length-1;i++) { System.out.print(a[i]+" "); } System.out.println(); sort bulbbleSort=new sort(); bulbbleSort.maopao(a); System.out.println("冒泡排序之后的数组顺序"); for(int i=0;i<=a.length-1;i++) { System.out.print(a[i]+" "); } } } python实现冒泡排序 附:因为for的循环只能从头开始,所以得先确定最后一位 def bubble_sort(items):     a=len(items)   #列表的长度     for i in range(a-1):         for j in range(a-i-1):             if(items[j]>items[j+1]):#先确定最后一位数的位置                 items[j],items[j+1]=items[j+1],items[j]#对两位数进行交换         return items arr=[44,55,6,98,56,88,74] print(bubble_sort(arr))

     

    Processed: 0.010, SQL: 8