就一个快速排序。。。

来源:互联网 发布:淘宝店铺名字大全女装 编辑:程序博客网 时间:2024/05/18 02:57

话说,每次写题的时候我都是调用STL的sort,自己却还是很难快速写出一个快排。。正好作业布置这个了。。就写一下,熟练一下,顺便背一下记住。。

万一以后面试问到了,也可以秒了。。


#include <iostream>#include <cstdio>#include <algorithm>using namespace std;const int maxn = 10000 + 5;double A[maxn];template <class T>T part(T a[], int p, int r){    int i = p, j = r;    T x = a[p];    while(i < j)    {        while(a[i] <= x && i <= j) i++;        while(a[j] >= x && j >= i) j--;        if(i >= j) break;        swap(a[i], a[j]);    }    a[p] = a[j];    a[j] = x;    return j;}template <class T>void quickSort(T a[], int p, int r){    if(p < r)    {        T q = part(a, p, r);        quickSort(a, p, q - 1);        quickSort(a, q + 1, r);    }}int main(){    freopen("input.txt", "r", stdin);    double A[maxn], x;    int cnt = 0;    while(cin >> x) {A[cnt++] = x;}    quickSort(A, 0, cnt - 1);    for(int i = 0; i < cnt; i++)    {        cout << A[i] << " ";        if((i + 1) % 10 == 0) cout << endl;    }    return 0;}


0 0
原创粉丝点击