代码、课程参考:
10.1.1 算法概述;10.1.2 选主元;10.1.3 子集划分;10.1.4 算法实现;
算法可视化:
https://www.cs.usfca.edu/~galles/visualization/Algorithms.html
浙江大学陈越姥姥开的这门数据结构讲解非常细致,强烈推荐!1.5倍速播放学习效率极高!
网上有的代码看了下都比较长,陈越姥姥给的算法思路较清晰,代码量少,遂记录之。
算法简介
快速排序的思想是首先选取一个主元,然后将待排序的数组分成大于主元和小于主元的部分,继续对这两部分递归进行快速排序,直至排序完成。
在陈越老师的课程里,主元的选取通过Median3函数实现。这个函数的功能是对待排序数组最左边,中间,最右边的数先进行排序,然后返回中间的数。
快速排序的主要内容还是建议观看视频,这里不再赘述。
C++实现
#include <stdio.h>
#include<iostream>
using namespace std;
int Median3(int A[], int Left, int Right) {
int Center = (Right + Left) / 2;
if (A[Left] > A[Center])
swap(A[Left], A[Center]);
if (A[Left] > A[Right])
swap(A[Left], A[Right]);
if (A[Center] > A[Right])
swap(A[Center], A[Right]);
/*A[Left] <= A[Center] <= A[Right]*/
swap(A[Center], A[Right - 1]);//将主元Pivot藏到右边
return A[Right - 1];
}
void Quicksort(int A[], int Left, int Right) {
if (Left >= Right) return;
int Pivot = Median3(A, Left, Right);
int i = Left, j = Right-1;
while(i<j){
while (A[++i]<Pivot){}
while (A[--j]>Pivot){}
if (i < j)
swap(A[i], A[j]);
}
swap(A[i], A[Right - 1]);
Quicksort(A, Left, i - 1);
Quicksort(A, i+1,Right);
}
int main() {
int n;
cout << "input the size of array" << endl;
cin >> n;
int *a = new int[n];
cout << "input the array" << endl;
for (int i = 0;i<n;i++) cin >> a[i];
Quicksort(a, 0, n - 1);
for (int i = 0;i<n;i++) {
if (i == 0) cout << a[i];
else cout << ' ' << a[i];
}
cout << endl;
delete[]a;
system("pause");
return 0;
}
不使用Median3函数选取主元:
#include <stdio.h>
#include<iostream>
using namespace std;
void Quicksort(int a[],int left,int right) {
if (left >= right) return;
int Pivot = a[right];
int i = left-1, j = right;
while (i < j) {
while (a[++i] < Pivot);
while (a[--j] > Pivot);
if(i<j)
swap(a[i], a[j]);
}
swap(a[i], a[right]);
Quicksort(a, left, i - 1);
Quicksort(a, i + 1, right);
}
int main() {
int n;
cin >> n;
int *a = new int[n];
for (int i = 0;i < n;i++) cin >> a[i];
Quicksort(a, 0, n - 1);
for (int i = 0;i < n;i++) {
if (i == 0) cout << a[i];
else cout << ' ' << a[i];
}
cout << endl;
delete[]a;
system("pause");
return 0;
}