public class 快速排序 {
public static void main(String[] args) {
int[] arr = {1, 2, 333, 0, 2, -1, -1, 333333, 342532515};
quickSort(arr, 0, arr.length - 1);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
private static void quickSort(int[] arr, int l, int r) {
int low = l, high = r;
if (low >= high) return;
int tem = arr[low];
while (low < high) {
while (arr[high] > tem && low < high) high--;
if (low < high) {
arr[low] = arr[high];
low++;
}
while (arr[low] < tem && low < high) low++;
if (low < high) {
arr[high] = arr[low];
high--;
}
}
//high == low, 说明high现在处于的位置右边是大于tem的,当前和左边是不大于tem的,直接将当前位置元素赋值:tem,
//而且不用担心arr[high]被覆盖,因为arr[high]的值已经被拿走了
arr[high] = tem;
quickSort(arr, l, high - 1);
quickSort(arr, high + 1, r);
}
}
时间复杂度:
快速排序时间复杂度:O(nlgn),在已经有序情况下:O(n2)
什么是不稳定性?
不稳定就是指:在排序过程中,相同元素的相对位置发生改变。