这是数据结构中比较经典排序算法:
#include <iostream>
using namespace std;
void QuickSort(char [], int, int);
int main()
{
char cset[20];
cout << "creating random char set!" << endl;
for (int i = 0; i < 20; i ++) {
cset[i] = 'A' + rand() % 26;
}
cout << "show the char set: " << endl;
for (int i = 0; i < 20; i++) {
cout << cset[i] << "\t";
if ((i+1)%5 == 0) {
cout << '\n';
}
}
QuickSort(cset, 0, 19);
cout << "after quick sort: " << endl;
for (int i = 0; i < 20; i++) {
cout << cset[i] << "\t";
if ((i+1)%5 == 0) {
cout << '\n';
}
}
return 1;
}
void QuickSort(char set[], int low, int high)
{
int beg = 0;
int end = 0;
char ctmp;
if (low < high) { // 若数组的 头 小于 尾(即数组长度大于1)
beg = low;
end = high;
ctmp = *(set + low);
} else { // 否则退出
return;
}
while (beg < end) // 两边向中间
{
while (beg < end && *(set + end) >= ctmp)
{
end--;
}
if (beg < end) {
*(set + beg) = *(set + end);
beg++;
}
while (beg < end && *(set + beg) <= ctmp)
{
beg++;
}
if (beg < end) {
*(set + end) = *(set + beg);
end--;
}
}
*(set + beg) = ctmp;
QuickSort(set, low, beg - 1); // 递归调用前半部分
QuickSort(set, beg + 1, high); // 递归调用后半部分
return;
}