1.双边循环法
子循环内是先从右往左找还是先从左往右找,取决于基准元素的位置是首还是尾。
#include <iostream>
#include <time.h>
using namespace std;
const int N = 16;
const int C = 64;
// 对数组的[low,high]区间进行一次划分,返回基准元素的位置
int partition(int a[], int low, int high) {
int pivot = low;
while (low < high) {
while (low < high && a[high] >= a[pivot]) {
high--;
}
while (low < high && a[low] <= a[pivot]) {
low++;
}
if (low < high) {
int t = a[high];
a[high] = a[low];
a[low] = t;
}
}
int t = a[pivot];
a[pivot] = a[low];
a[low] = t;
return low; // 基准元素的位置
}
void qSort(int a[], int low, int high) {
if (low < high) {
// 分成两个子序列
int pivotIndex = partition(a, low, high);
qSort(a, low, pivotIndex - 1);
qSort(a, pivotIndex + 1, high);
}
}
void init(int a[], int n) {
srand(time(NULL));
printf("排序前的随机数组:\n");
for (int i = 0; i < n; i++) {
a[i] = rand() % C;
cout << a[i] << " ";
}
}
void check(int a[], int n) {
for (int i = 1; i < n; i++) {
if (a[i] < a[i - 1]) {
printf("排序出错");
return;
}
}
printf("\n完成快速排序后的数组:\n");
for (int i = 0; i < N; i++) {
cout << a[i] << " ";
}
}
int main() {
int a[N] = {0};
init(a, N);
qSort(a, 0, N - 1);
check(a, N);
return 0;
}
2.单边循环法
只有partition的实现与双边循环法不同
#include <iostream>
#include <time.h>
using namespace std;
const int N = 16;
const int C = 64;
// 对数组的[low,high]区间进行一次划分,返回基准元素的位置
int partition(int a[], int low, int high) {
int pivot = a[low];
int pivotIndex = low;
for (int i = low + 1; i <= high; i++) {
if (a[i] < pivot) {
pivotIndex++;
int t = a[pivotIndex];
a[pivotIndex] = a[i];
a[i] = t;
}
}
a[low] = a[pivotIndex];
a[pivotIndex] = pivot;
return pivotIndex; // 基准元素的位置
}
void qSort(int a[], int low, int high) {
if (low < high) {
// 分成两个子序列
int pivotIndex = partition(a, low, high);
qSort(a, low, pivotIndex - 1);
qSort(a, pivotIndex + 1, high);
}
}
void init(int a[], int n) {
srand(time(NULL));
printf("排序前的随机数组:\n");
for (int i = 0; i < n; i++) {
a[i] = rand() % C;
cout << a[i] << " ";
}
}
void check(int a[], int n) {
for (int i = 1; i < n; i++) {
if (a[i] < a[i - 1]) {
printf("排序出错");
return;
}
}
printf("\n完成快速排序后的数组:\n");
for (int i = 0; i < N; i++) {
cout << a[i] << " ";
}
}
int main() {
int a[N] = {0};
init(a, N);
qSort(a, 0, N - 1);
check(a, N);
return 0;
}