Java BubbleSort
package sort.bubble; import java.util.Arrays; public class BubbleSort { public static void main(String[] args) { int[] arr = {6,8,4,7,9,12}; bubbleSort(arr); //bubbleSort2(arr); //bubbleSort1(arr); } /*交换次数最少的冒泡排序 * 冒泡排序,根据最后交换数位置 */ public static void bubbleSort(int[] arr) { int start = 0; //未排序数组开始位置 int end =arr.length; //未排序数组结束位置 int current; //未排序数组当前位置 int last; //未排序数组最后一次发生交换的位置 while(start <end) { current = last = start; while(++current <end) { if(arr[current] < arr[current-1]) { last = current; //当前位置发生交换,记录改变位置 int temp = arr[current]; arr[current]= arr[current -1]; arr[current-1] = temp; } System.out.println(Arrays.toString(arr)); } end = last; System.out.println("--"+Arrays.toString(arr) +" " +last); } System.out.println("@@ "+Arrays.toString(arr)); } public static void bubbleSort1(int[] arr) { int len = arr.length -1; for(int i =0;i<len;i++) { for(int j= i+1;j<len+1;j++) { if(arr[i] < arr[j]) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } System.out.println(Arrays.toString(arr)); } System.out.println("-----"+Arrays.toString(arr)); } } //第二版本,减少每一趟的次数 public static void bubbleSort2(int[] arr){ boolean sorted= true; int len =arr.length; for(int j=0;j<len-1;j++){ //趟数 sorted =true; //假定有序 for(int i=0;i<len-1-j;i++){ //次数 if(arr[i]>arr[i+1]){ int temp = arr[i]; arr[i] =arr[i+1]; arr[i+1] =temp; sorted =false; //假定失败 } System.out.println(Arrays.toString(arr)); } if(sorted){ //减少趟数 break; } System.out.println("-----"+Arrays.toString(arr)); } } }
I don't extravagant hope to change the world, only hope this world will not change me.