提示:
假设两个数a和b,将a异或b的值记做temp,即:
temp=a^b;
那么temp^ a的值为b,并且temp^b的值为a
package sort;
import java.util.Arrays;
/**
* @author Zhujintao 2021/2/5 13:27
* @desc BubbleSort.
*/
public class BubbleSort {
/**
* 简单冒泡排序
* @param arr
*/
public static void bubbleSort1(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j] ^ arr[j + 1];
arr[j + 1] = temp ^ arr[j + 1];
arr[j] = arr[j] ^ temp;
}
}
}
System.out.println(Arrays.toString(arr));
}
/**
* 优化一:添加一个标志,当数组循环遍历时某次循环不再交换元素位置表示排序完成,避免了固定循环次数导致的数组排序完成仍然循环遍历的问题
* 适用于少量数据乱序的数组.
*
* @param arr
*/
public static void bubbleSort2(int[] arr) {
for (int i = 0; i < arr.length - 1 ; i++) {
boolean isExchange = false;
for (int j = 0; j < arr.length - i - 1 ; j++) {
if (arr[j] > arr[j+1]) {
int temp = arr[j] ^ arr[j + 1];
arr[j + 1] = temp ^ arr[j +1];
arr[j] = temp ^ arr[j];
isExchange = true;
}
}
if (!isExchange) {break;}
}
System.out.println(Arrays.toString(arr));
}
/**
* 优化二:每次记录交换位置的元素下标,下次只需遍历到此即可,因为后面的已经是有序了。
* 适用于前面大部分无序,后面大部分有序的数组.
*
* @param arr
*/
public static void bubbleSort3(int[] arr) {
int index = 0;
int len = arr.length - 1;
for (int i = 0; i < arr.length - 1; i++) {
boolean isExchenge = false;
for (int j = 0; j < len; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j] ^ arr[j + 1];
arr[j + 1] = temp ^ arr[j + 1];
arr[j] = temp ^ arr[j];
index = j;
isExchenge = true;
}
}
len = index;
if (!isExchenge){break;}
}
System.out.println(Arrays.toString(arr));
}
/**
* 优化三:正向扫描找到最大值交换到最后,反向扫描找到最小值交换到最前面。
*
* @param arr
*/
public static void bubbleSort4(int[] arr) {
int maxIndex = 0;
int minIndex = 0;
for (int i = 0; i < arr.length - 1 ; i++) {
boolean isExchenge = false;
for (int j = 0; j < arr.length - 1 ; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j] ^ arr[j + 1];
arr[j + 1] = temp ^ arr[j + 1];
arr[j] = temp ^ arr[j];
maxIndex = j;
isExchenge = true;
}
}
for (int m = maxIndex; m > minIndex ; m--) {
if (arr[m] < arr[m - 1]) {
int temp = arr[m] ^ arr[m - 1];
arr[m - 1] = temp ^ arr[m - 1];
arr[m] = temp ^ arr[m];
minIndex = m;
isExchenge = true;
}
}
if (!isExchenge){break;}
}
System.out.println(Arrays.toString(arr));
}
public static void main(String[] args) {
int[] arr = {3, 2, 1, 5, 4, 7, 6, 8, 9, 10, 11, 0};
bubbleSort1(arr);
int[] arr2 = {3, 2, 1, 5, 4, 7, 6, 8, 9, 10, 11, 0};
bubbleSort2(arr2);
int[] arr3 = {3, 2, 1, 5, 4, 7, 6, 8, 9, 10, 11, 0};
bubbleSort3(arr3);
int[] arr4 = {3, 2, 1, 5, 4, 7, 6, 8, 9, 10, 11, 0};
bubbleSort4(arr4);
}
}