基本思想:
通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。
快速排序是一种不稳定的排序方法,最差情况下其时间复杂度为O(n²),最好情况下为O(n logn),所以平均时间复杂度为O(n lg n/lg 2);
代码:
package book;
import java.util.Scanner;
public class SMC {
public static void qsort_asc(int source[], int low, int high) {
int i, j, x;
if (low < high) {
i = low;
j = high;
x = source[i];
while (i < j) {
while (i < j && source[j] > x) {
j--;
}
if (i < j) {
source[i] = source[j];
i++;
}
while (i < j && source[i] < x) {
i++;
}
if (i < j) {
source[j] = source[i];
j--;
}
}
source[i] = x;
qsort_asc(source, low, i - 1);
qsort_asc(source, i + 1, high);
}
}
public static void main(String[] args) {
// int[] a = { 4, 2, 1, 6, 3, 6, 0, -5, 1, 1 };
System.out.println("请输入数组的大小:");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[] = new int[n];
System.out.println("请输入数组的元素:");
for (int i = 0; i < a.length; i++) {
a[i] = sc.nextInt();
}
sc.close();
int i;
qsort_asc(a, 0, a.length - 1);
System.out.println("最终的排序为:");
for (i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}