1.什么是快速排序
- 选定数组中一个数为基准数(此文以数组第一个数作为基准数,个人习惯如此)。
- 分别从最左和最右遍历数组,将大于基准数的数放在其右边,小于基准数的数放在其左边。
递归方式重复步骤2,直到各区间只有一个数或为空。
*快速排序被认为是所有O(N*logN)排序算法中效率最高的。
2.时间复杂度&空间复杂度
最好情况:O(N*logN)
平均情况:O(N*logN)
最坏情况:O(N^2)
空间占用S(1),只需花费常数级的空间。
3.代码实现(Java实现)
public class QuickSort {
public void sort(int temp[]) {
quickSort(temp, 0, temp.length - 1);
}
private void quickSort(int[] temp, int low, int high) {
if (low < high) {
int des = getDes(temp, low, high);
quickSort(temp, low, des-1);
quickSort(temp, des+1, high);
}
}
private int getDes(int[] temp, int low, int high) {
int t = temp[low]; //缓存基准数
while (low < high) {
while (low < high && temp[high] > t) {
high--;
}
temp[low] = temp[high];
while (low < high && temp[low] < t) {
low++;
}
temp[high] = temp[low];
}
temp[low] = t; //将基准数赋值给空缺位
return low;
}
}