快速排序算法
/**
* 快速排序
*/
public static int[] quickSort(int[] array) {
quick(array);
return array;
}
private static int getMiddle(int[] list, int low, int high) {
int tmp = list[low];
while (low < high) {
while (low < high && list[high] >= tmp) {
high--;
}
list[low] = list[high];
while (low < high && list[low] <= tmp) {
low++;
}
list[high] = list[low];
}
list[low] = tmp;
return low;
}
private static void middleSort(int[] list, int low, int high) {
if (low < high) {
int middle = getMiddle(list, low, high);
middleSort(list, low, middle - 1);
middleSort(list, middle + 1, high);
}
}
private static void quick(int[] a2) {
if (a2.length > 0) {
middleSort(a2, 0, a2.length - 1);
}
}
运行
/**
* 待排序的数组
*/
private static int[] array = {
12, 10, 5, 9, 5, 32, 16, 1, 9, 99, 80, 3, 18, 19, 20, 25, 7, 15
};
public static void main(String[] args) {
int[] result = SortUtils.quickSort(array.clone());
System.out.println(Arrays.toString(result));
}
输出
[1, 3, 5, 5, 7, 9, 9, 10, 12, 15, 16, 18, 19, 20, 25, 32, 80, 99]
网友评论