快速排序如同其名,是排序中性能比较好的一个排序算法。当数组是顺序的话,他的最差的时间复杂度是O(N^2),其他一般的时间复杂度是O(n*lgn).,也是不稳定的排序算法。
快速排序的思想就是分治,每一趟排序过程都把一个数放到最终的位置上面去。然后这个位置把数组分为前半部分和后半部分。针对前半部分和后半部分再递推进行快速排序。
快排的java实现:
public class Sort {
public static void main(String[] args) {
int[] a = { 6,5,4,3,2,1,0,9,8,7};
quickSort(a, 0, a.length - 1);
for (int s : a) {
System.out.println(s);
}
}
public static int quickSortDiv(int[] a, int i, int j) {
int temp;
int key = a[i];
while (i < j) {
while (i < j && a[j] >= key) {
j--;
}
if (i < j) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
while (i < j && a[i] < key) {
i++;
}
if (i < j) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
return i;
}
public static void quickSort(int[] a, int i, int j) {
if (i < j) {
int m = quickSortDiv(a, i, j);
quickSort(a, m+1, j);
quickSort(a, i, m-1);
}
}
}