1.算法步骤
- 从数列中挑出一个元素,称为 “基准”(pivot);
- 重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆在基准的后面(相同的数可以到任一边)。在这个分区退出之后,该基准就处于数列的中间位置。这个称为分区(partition)操作;
- 递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序。
2.动图演示![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d9ec8b735302086f894da12c7fe8245b.gif)
3.代码实现
第一种:分区递归
//严蔚敏《数据结构》标准分割函数
Paritition(int A[], int low, int high) { //low,high为数组始末下标
int pivot = A[low]; //基准
while (low < high) {
while (low < high && A[high] >= pivot) {
--high;
}
A[low] = A[high];
while (low < high && A[low] <= pivot) {
++low;
}
A[high] = A[low];
}
A[low] = pivot;
return low;
}
void QuickSort(int A[], int low, int high) //快排母函数
{
if (low < high) {
int pivot = Paritition(A, low, high);
QuickSort(A, low, pivot - 1);
QuickSort(A, pivot + 1, high);
}
}
第二种:递归
void quickSort(int arr[], int start, int end){ //start和end为数组始末下标
if(start >= end)
return;
int mid = arr[end];
int left = start, right = end - 1;
while (left < right) { //在整个范围内搜寻比枢纽元值小或大的元素,然后将左侧元素与右侧元素交换
while (arr[left] < mid && left < right) //试图在左侧找到一个比枢纽元更大的元素
left++;
while (arr[right] >= mid && left < right) //试图在右侧找到一个比枢纽元更小的元素
right--;
swap(arr[left], arr[right]); //交换元素
}
if (arr[left] >= arr[end])
swap(arr[left], arr[end]);
else
left++;
quickSort(arr, start, left - 1);
quickSort(arr, left + 1, end);
}