快速排序算法和合并排序算法一样,也是基于分治模式。对子数组A[p...r]快速排序的分治过程的三个步骤为:
分解:把数组A[p...r]分为A[p...q-1]与A[q+1...r]两部分,其中A[p...q-1]中的每个元素都小于等于A[q]而A[q+1...r]中的每个元素都大于等于A[q];
解决:通过递归调用快速排序,对子数组A[p...q-1]和A[q+1...r]进行排序;
合并:因为两个子数组是就地排序的,所以不需要额外的操作。
快速排序算法的伪代码:
- QUICKSORT(A, p < r) {
- 1 if p <
r { - 2 q = PARTITION(A, p, r);
- 3 QUICKSORT(a, p, q-1);
- 4 QUICKSORT(a, q+1, r);
- 5 }
- }
这个 算法的关键在于数组的划分,即PARTITION:
- PARTITION(A, p, r) {
- 1 x = A[r];
- 2 i = p-1;
- 3 for j = p to r-1 {
- 4
if A[j] ≤ x { - 5
i = i + 1; - 6
exchange(A[i], A[j]); - 7
} - 8 }
- 9
exchange(A[i+1], A[r]); - 10 return i+1;
- }
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
//交换数据
void exchange(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
//指定范围随机数
int Random(int n, int m)
{
int pos, dis;
pos = n;
dis = m - n + 1;
srand((int)time(NULL));
return rand() % dis + pos;
}
//对数组进行划分
int Partition(int *A, int p, int r) //p,r均为数组下标
{
int x = A[r];
int i = p - 1;
for (int j = p; j < r; j++)
{
if (A[j] < x)
{
i = i + 1;
exchange(A[i], A[j]);
}
}
exchange(A[i + 1], A[r]);
return i + 1;
}
//快速排序
void QuickSort(int *A, int p, int r)
{
if (p < r)
{
int q = Partition(A, p, r);
QuickSort(A, p, q - 1);
QuickSort(A, q + 1, r);
}
}
/*下面是随机生成主元*/
//随机划分
int RandomPartition(int *A, int p, int r)
{
int i = Random(p, r);
exchange(A[r], A[i]);
return Partition(A, p, r);
}
//随机快速排序
void RandomQuickSort(int *A, int p, int r)
{
if (p < r)
{
int q = RandomPartition(A, p, r);
RandomQuickSort(A, p, q - 1);
RandomQuickSort(A, q + 1, r);
}
}
int main()
{
int n = 1, m = 5;
cout <<"随机数:"<< Random(n, m) << endl;
int a[] = { 1, 3, 4, 6, 3, 6, 9, 12, 10, 8 };
RandomQuickSort(a, 0, 9);
for (int i = 0; i < 10; i++)
cout << a[i] << endl;
}