1.快速排序基本思路:
- 在待排序的N个记录中任取一个元素(通常取第一个记录),我们把它叫做哨兵。
- 义两个索引 i 和 j 分别表示“首索引” 和 “尾索引”,temp表示“哨兵”。
- 首先,尾索引向前扫描,直到找到比基准值小的记录(i != j),并替换首索引对应的值。
- 然后,首索引向后扫描,直到找到比基准值大于的记录(i!= j),并替换尾索引对应的值。
- 在扫描过程中首索引等于尾索引(i= j),则一趟排序结束;将哨兵(temp)替换首索引所对应的值。
- 再进行下一趟排序时,待排序列被分成两个区:[0,i-1],[j+1,end]。
- 对每一个分区重复步骤2~6,直到所有分区中的记录都有序,排序成功。
2.图解:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200311173220643.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzcwNjY2NA==,size_16,color_FFFFFF,t_70)
3.代码实现:
public class QuickSort {
public static void main(String[] args) {
int[] arr = {6, 1, 2, 7, 9, 3, 4, 5, 10, 8};
quicksort(arr, 0, arr.length - 1);
for (int x : arr) {
System.out.print(x + " ");
}
}
private static void quicksort(int[] arr, int low, int high) {
if (low > high) {
return;
}
int i, j, temp, t;
i = low;
j = high;
temp = arr[low];
while (i < j) {
while (temp <= arr[j] && i < j) {
j--;
}
while (temp >= arr[i] && i < j) {
i++;
}
if (i < j) {
t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
int a = arr[low];
arr[low] = arr[i];
arr[i] = a;
quicksort(arr, low, j - 1);
quicksort(arr, j + 1, high);
}
}