快速排序算法思想的资料很多,这边只展示用C++ 实现的快速排序算法:
#include <stdio.h>
#include <stdlib.h>
void quickSort(int arr[], int nLen)
{
if (nLen <= 1) {
return;
}
int n = arr[0];
int l = 0;
int r = nLen - 1;
while (l < r) {
while (arr[r] > n && l < r) r--; // 查找小于等于基数的元素
while (arr[l] <= n && l < r) l++; // 查找大于基数的元素
if (l == r) {
if (0 != r) {
arr[0] ^= arr[r];
arr[r] ^= arr[0];
arr[0] ^= arr[r];
}
break;
} else {
arr[l] ^= arr[r];
arr[r] ^= arr[l];
arr[l] ^= arr[r];
}
}
int rLen = nLen - r - 1;
// 有先处理较少的数据,减少调用栈的深度
if (rLen > l) {
quickSort(arr, l);
quickSort(&arr[r+1], rLen);
} else {
quickSort(&arr[r+1], rLen);
quickSort(arr, l);
}
}
int main()
{
int arr[100] = {0};
int nLen = 100;
for (size_t i = 0; i < nLen; i++)
{
arr[i] = rand() % nLen;
printf("%d, ", arr[i]);
}
printf("\r\n\r\n");
quickSort(arr, nLen);
for (size_t i = 0; i < nLen; i++)
{
printf("%d, ", arr[i]);
}
return 0;
}