
image.png
/**
* 冒泡排序
* @param intArray 待排序数组
* @param rules 排序规则/desc|asc
*/
public static void popSort(int[] intArray, String rules) {
if (!(intArray.length==1)){
if ("desc".equals(rules)) {
//总共需要比较元素数量-1轮
for (int i = 0; i < intArray.length - 1; i++) {
//如果不-1,就会使最后一个和最后一个+1个进行比较,从而抛出越界异常
for (int j = 0; j < intArray.length - 1; j++) {
if (intArray[j] < intArray[j + 1]) {
intArray[j] = intArray[j + 1] ^ intArray[j];
intArray[j + 1] = intArray[j + 1] ^ intArray[j];
intArray[j] = intArray[j + 1] ^ intArray[j];
}
}
}
}
if ("asc".equals(rules)){
for (int i = 0; i < intArray.length - 1; i++) {
for (int j = 0; j < intArray.length - 1; j++) {
if (intArray[j] > intArray[j + 1]) {
intArray[j] = intArray[j + 1] ^ intArray[j];
intArray[j + 1] = intArray[j + 1] ^ intArray[j];
intArray[j] = intArray[j + 1] ^ intArray[j];
}
}
}
}
}else{
return;
}
}