快速排序的基本思想是在待排序的n个元素中任取一个元素(通常取第一个元素)作为基准,把该元素放入最终位置后,整个数据序列被基准分割成两个子序列,所有小于基准的元素放在前子序列中,所有大于基准的元素放置在后子序列中,并把基准排在这两个子序列的中间,这个过程称为划分。然后对两个子序列分别重复上述过程,直到每个子序列内只有一个元素或空为止。
#include <iostream>
using namespace std;
void disp(int a[], int n) {
int i;
for (i = 0; i < n; i++) {
cout << a[i] << '\t';
}
cout << endl;
}
int Parition(int a[], int s, int t) {
int i = s, j = t, c;
int tmp = a[s];
while (i != j) {
while (j > i && a[j] >= tmp)
j--;
c = a[i];
a[i] = a[j];
a[j] = c;
while (i < j && a[i] <= tmp)
i++;
c = a[j];
a[j] = a[i];
a[i] = c;
}
return i;
}
void QuickSort(int a[], int s, int t) {
if (s < t) {
int i = Parition(a, s, t);
QuickSort(a, s, i - 1);
QuickSort(a, i + 1, t);
}
}
int main() {
int n = 10;
int a[] = { 3, 1, 5, 8, 10, 9, 6, 4, 2, 7 };
cout << "排序前" << endl;
disp(a, n);
QuickSort(a, 0, n - 1);
cout << "排序后" << endl;
disp(a, n);
return 0;
}