算法描述
快速排序(Quicksort)是对冒泡排序的一种改进。
它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。
递归版:
/*递归写法 10.3
最好、平均时间复杂度O(NlogN) 空间复杂度O(logN)
最差时间复杂度O(N*N) 空间复杂度O(N) 退化成冒泡排序
不稳定*/
public static void quicksort(int a[]){
quicksort(a, 0, a.length-1);
}
public static void quicksort(int a[], int low, int high){
if (low > high) {
return;
}
int i = low;
int j = high;
int index = a[low];
while (i < j) {
while (i<j && a[j]>=index) {
j--;
}
if (i < j) {
a[i++] = a[j];
}
while (i<j && a[i]<=index) {
i++;
}
if (i < j) {
a[j--] = a[i];
}
a[i] = index;
quicksort(a, low, i-1);
quicksort(a, i+1, high);
}
}
public static void main(String[] args) {
int a[] = { 49, 38, 65, 97, 76, 13, 27, 49,78 ,48646,4896,48,64,465,64 };
quicksort(a);
System.out.println(Arrays.toString(a));
}
非递归版:
public static void quicksort(int a[]){
int i,j,index,low,high,temp;
Stack<Integer> stack = new Stack<Integer>();
stack.push(0);
stack.push(a.length-1);
while (!stack.isEmpty()) {
high = stack.pop();
low = stack.pop();
index = a[low];
i = low;
j = high;
while (i<j) {
while (i<j && a[j]>=index) {
j--;
}
while (i<j && a[i]<=index) {
i++;
}
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
if (index > a[i]) {
temp = a[low];
a[low] = a[j];
a[j] = temp;
}
if (low < i-1) {
stack.push(low);
stack.push(i-1);
}
if (high > i+1) {
stack.push(i+1);
stack.push(high);
}
}
}
运行结果: