Chinaunix首页 | 论坛 | 博客
  • 博客访问: 32552
  • 博文数量: 35
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 360
  • 用 户 组: 普通用户
  • 注册时间: 2021-09-17 18:39
文章分类

全部博文(35)

文章存档

2021年(35)

我的朋友

分类: C/C++

2021-09-29 13:04:25

#include
#include
#include


using namespace std;


template
void quicksort(T B[], int lo, int hi);
template
int Partition(T B[], int lo, int hi);


int main() {


    int a[] = {6,5,0,1,34,9,4,4,4,2,-1};
    for(int i = 0; i < 11; i++)
        cout << a[i] << ",";
    cout << endl;


    quicksort(a, 0, 11);
   
    for(int i = 0; i < 11; i++)
        cout << a[i] << ",";
    cout << endl;


    return 0;
}


template
void quicksort(T B[], int lo, int hi) {
    if(hi - lo < 2) return;
   
    int mi = Partition(B, lo, hi - 1);


    quicksort(B, lo, mi);
    quicksort(B, mi+1, hi);
}


template
int Partition(T B[], int lo, int hi) {
    swap(B[lo], B[rand()%(hi - lo)]);
    T pivot = B[lo];


    while(lo < hi) {
        while(pivot <= B[hi])
            hi--;
        B[lo] = B[hi];


        while(B[lo] <= pivot)
            lo++;
        B[hi] = B[lo];
    }


    B[lo] = pivot;


    return lo;
}
阅读(697) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~