排序
/**
* 冒泡算法
*/
private static void bubbleSort() {
int[] arr = {3, 1, 2, 8, 4, 6, 9, 5};
//元素
for (int i =0; i < arr.length; i++) {
//比较的次数
for (int j =0; j < arr.length -1 - i; j++) {
if (arr[j] > arr[j +1]) {
int temp = arr[j];
arr[j] = arr[j +1];
arr[j +1] = temp;
}
}
for (int x =0; x < arr.length; x++) {
System.out.print("值: " + arr[x] +",");
}
System.out.println("");
}
}
/**
* 快排算法
*
* @param array
*/
public static void quickSort(int[] array) {
int len;
if (array ==null
|| (len = array.length) ==0
|| len ==1) {
return;
}
sort(array, 0, len -1);
}
public static void sort(int[] array, int left, int right) {
if (left > right) {
return;
}
int base = array[left];
int i = left, j = right;
while (i != j) {
// 顺序很重要,先从右边开始往左找,直到找到比base值小的数
while (array[j] >= base && i < j) {
j--;
}
// 再从左往右边找,直到找到比base值大的数
while (array[i] <= base && i < j) {
i++;
}
if (i < j) {
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
array[left] = array[i];
array[i] = base;
sort(array, left, i -1);
sort(array, i +1, right);
}