快排这个算法早就已经学过,一般直接使用STL里的sort()就可以了,粗略的想一下,貌似觉得非常的简单。就算这样,在自己具体动手去实现的时候还是遇到一些问题,比如排序的具体流程,怎么尽量减少时间与空间的复杂度以及使用模板类,及比较函数的传入等。
最后实现了跟<algorithm>里sort基本一样的功能,C++代码及测试如下:
#include <iostream>
#include <cmath>
#include <queue>
#include <stack>
#include <random>
#include <vector>
#include <algorithm>
using namespace std;
int cnt = 0;
template<class T>
void mySort(T *__begin, T *__end)
{
cnt++;
if (__end - __begin <= 1) return;
T mid = *(__begin + (__end - __begin - 1)/2);
T *begin = __begin, *end = __end - 1;
while (begin <= end)
{
while (begin<=end && *begin < mid)
{
begin++;
}
while (begin <=end && mid < *end)
{
end--;
}
if (begin <= end)
{
swap(*begin, *end);
begin++;
end--;
}
}
mySort(__begin, end+1);
mySort(begin, __end);
}
template<class T, class Comp>
void mySort(T *__begin, T *__end, Comp *cmp)
{
cnt++;
if (__end - __begin <= 1) return;
T mid = *(__begin + (__end - __begin - 1) / 2);
T *begin = __begin, *end = __end - 1;
while (begin <= end)
{
while (begin <= end && cmp(*begin, mid))
{
begin++;
}
while (begin <= end && cmp(mid, *end))
{
end--;
}
if (begin <= end)
{
swap(*begin, *end);
begin++;
end--;
}
}
mySort(__begin, end + 1, cmp);
mySort(begin, __end, cmp);
}
bool comp(int a, int b)
{
return a < b;
}
struct node
{
int x, y;
node()
{
x = rand();
y = rand();
}
bool operator < (node a)
{
if (a.x == x) return y < a.y;
return x < a.x;
}
};
bool cmp2(node a, node b)
{
return a.x > b.x;
}
int main()
{
const int N = 128;
int go[N];
srand(rand());
for (int i = 0; i < N; i++) go[i] = rand();
for (int i = 0; i < N; i++) cout << i << '-' << go[i] << " ";
cout << endl;
sort(go, go + N, comp);
mySort(go, go + N, comp);
for (int i = 0; i < N; i++) cout << i << '-' << go[i] << " ";
cout << endl <<"Sort() function called "<< cnt << " times!"<< endl;
for (int i = 1; i < N; i++) if (go[i] < go[i - 1]) cout<<i << " Sort result is not OK!" << endl;
const int M = 12;
node a[M];
for (int i = 0; i < M; i++) cout << i << ' ' << a[i].x << ' ' << a[i].y << endl;
sort(a, a + M);
for (int i = 0; i < M; i++) cout << i << ' ' << a[i].x << ' ' << a[i].y << endl;
sort(a, a + M, cmp2);
for (int i = 0; i < M; i++) cout << i << ' ' << a[i].x << ' ' << a[i].y << endl;
}