image.png
/**
* 冒泡排序
* @param intArray 待排序數(shù)組
* @param rules 排序規(guī)則/desc|asc
*/
public static void popSort(int[] intArray, String rules) {
if (!(intArray.length==1)){
if ("desc".equals(rules)) {
//總共需要比較元素?cái)?shù)量-1輪
for (int i = 0; i < intArray.length - 1; i++) {
//如果不-1,就會使最后一個和最后一個+1個進(jìn)行比較,從而拋出越界異常
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;
}
}