packagecom.zby.sort;/***@authorzby
* @title BubbleSort
* @date 2019年7月9日
* @description 冒泡排序*/
public classBubbleSort {public static voidmain(String[] args) {
run(10);
run(10000);
run(100000);
}/*** 使用工具类排序
*
*@paramsize*/
private static void run(intsize) {int[] intArrayShiwan =SortUtil.getIntArray(size);
SortUtil.run("冒泡排序(临时变量交换)", intArrayShiwan, BubbleSort::bubbleSortWithTempExchange);
SortUtil.run("冒泡排序(异或交换)", intArrayShiwan, BubbleSort::bubbleSortWithXorExchange);
SortUtil.run("冒泡排序(趟数优化)", intArrayShiwan, BubbleSort::bubbleSortRanksOptimize);
SortUtil.run("冒泡排序(交换优化)", intArrayShiwan, BubbleSort::bubbleSortExchangeOptimize);
}/*** 冒泡排序(临时变量交换)
*
*@paramarr 待排序数组*/
public static void bubbleSortWithTempExchange(int[] arr) {inttemp;for (int i = 0; i < arr.length - 1; i++) {for (int j = 0; j < arr.length - 1 - i; j++) {if (arr[j] > arr[j + 1]) {
temp=arr[j];
arr[j]= arr[j + 1];
arr[j+ 1] =temp;
}
}
}
}/*** 冒泡排序(异或交换)
*
*@paramarr 待排序数组*/
public static void bubbleSortWithXorExchange(int[] arr) {for (int i = 0; i < arr.length - 1; i++) {for (int j = 0; j < arr.length - 1 - i; j++) {if (arr[j] > arr[j + 1]) {
arr[j]= arr[j] ^ arr[j + 1];
arr[j+ 1] = arr[j] ^ arr[j + 1];
arr[j]= arr[j] ^ arr[j + 1];
}
}
}
}/*** 冒泡排序比较趟数优化,但是多了判断、赋值
*
*@paramarr 待排序数组*/@Deprecatedpublic static void bubbleSortRanksOptimize(int[] arr) {inttemp;for (int i = 0; i < arr.length - 1; i++) {boolean ordered = true;for (int j = 0; j < arr.length - 1 - i; j++) {if (arr[j] > arr[j + 1]) {
temp=arr[j];
arr[j]= arr[j + 1];
arr[j+ 1] =temp;
ordered= false;
}
}if(ordered) {break;
}else{
ordered= true;
}
}
}/*** 冒泡排序交换优化(使用冒泡的方式找最大值,使用索引的方式一趟一次交换)
*
*@paramarr 待排序数组*/
public static void bubbleSortExchangeOptimize(int[] arr) {inttemp;intmaxIndex;for (int i = 0; i < arr.length - 1; i++) {int lastIndex = arr.length - i - 1;
maxIndex= 0;for (int j = 0; j <= lastIndex; j++) {if (arr[maxIndex]
maxIndex=j;
}
}if (lastIndex !=maxIndex) {
temp=arr[maxIndex];
arr[maxIndex]=arr[lastIndex];
arr[lastIndex]=temp;
}
}
}
}