最近讀了《數據結構與算法-C語言描述》,受益匪淺,裏面的排序算法講的淺顯易懂,而且給出的快速排序算法代碼也非常簡潔,下面給出中快排的遞歸和非遞歸方式(參考了別人代碼實現的),同時將快排的變種快速選擇算法的代碼也附上,方便記憶。代碼我已經調試通過可以直接使用或者用來記憶用來面試。
#include<iostream>
#include<stack>
using namespace std;
#define cutoff (3)
//三數取中
int Median3(int A[], int left, int right) {
int center = (left + right) / 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]);
swap(A[center], A[right - 1]);
return A[right - 1];
}
//插入排序
void InsertSort(int A[], int N) {
int j, P;
int tmp;
for (P = 1; P < N; P++) {
tmp = A[P];
for (j = P; j > 0 && A[j - 1] > tmp; j--)
A[j] = A[j - 1];
A[j] = tmp;
}
}
//快排遞歸版本
void Qsort(int A[], int left, int right) {
int i, j;
int pivot;
if (left + cutoff <= right) {
pivot = Median3(A, left, right);
i = left;
j = right - 1;
for (;;){
while (A[++i] < pivot) {}
while (A[--j] > pivot) {}
if (i < j)
swap(A[i], A[j]);
else
break;
}
swap(A[i], A[right - 1]);
Qsort(A, left, i - 1);
Qsort(A, i + 1, right);
}
else
InsertSort(A + left, right - left + 1);
}
//快速選擇遞歸版本 :查找數組A中第K大的數字
void Qselect(int A[], int k, int left, int right) {
int i, j;
int pivot;
if (left + cutoff <= right) {
pivot = Median3(A, left, right);
i = left;
j = right - 1;
for (;;){
while (A[++i] < pivot) {};
while (A[--j] > pivot) {};
if (i < j)
swap(A[i], A[j]);
else
break;
}
swap(A[i], A[right - 1]);
if (k <= i)
Qselect(A, k, left, i - 1);
else if (k > i + 1)
Qselect(A, k, i + 1, right);
}
else
InsertSort(A + left, right - left + 1);
}
//快排非遞歸版本
void QuickSortNotRNew(int* A, int left, int right)
{
int i, j;
int pivot;
stack<int> s;
s.push(left);
s.push(right);//後入的right,所以要先拿right
while (!s.empty())//棧不爲空
{
int right = s.top();
s.pop();
int left = s.top();
s.pop();
if (left + cutoff <= right) {
pivot = Median3(A, left, right);
i = left;
j = right - 1;
for (;;){
while (A[++i] < pivot) {};
while (A[--j] > pivot) {};
if (i < j)
swap(A[i], A[j]);
else
break;
}
swap(A[i], A[right - 1]);
int index = i;
if ((index - 1) > left)//左子序列
{
s.push(left);
s.push(index - 1);
}
if ((index + 1) < right)//右子序列
{
s.push(index + 1);
s.push(right);
}
}
else
InsertSort(A + left, right - left + 1);
}
}
int main() {
int i;
int a[] = { 10, 3, 6, 40, 1, 4, 9, 60, 30, 5, 2, 20, 50 };
int b[] = { 10, 3, 6, 40, 1, 4, 9, 60, 30, 5, 2, 20, 50 };
int ilen = (sizeof(a)) / (sizeof(a[0]));
int range = 3;
cout << "before sort:";
for (i = 0; i<ilen; i++)
cout << a[i] << " ";
cout << endl;
Qsort(a, 0, ilen - 1);
cout << "after sort:";
for (i = 0; i<ilen; i++)
cout << a[i] <<endl;
QuickSortNotRNew(b, 0, ilen - 1);
cout << "after Not recursive sort:";
for (i = 0; i<ilen; i++)
cout << b[i] <<endl;
Qselect(a, range - 1 , 0, ilen - 1);
cout << "the "<<range<<"th large number is:";
cout << a[range - 1] << endl;
return 0;
}
代碼運行結果
參考:《數據結構與算法-C語言描述》
https://blog.csdn.net/qq_36528114/article/details/78667034