快速排序C++代码

#include <iostream>

using namespace std;


template <class T>
void qSort(T *a, int left, int right);// 快速排序

template <class T>
void sW(T *a, T *b);

int main(){
    int a[] = {3, 4, 5, 12, -1, -33, 90, -44, -23, 100, -1111, -9};
    int len = sizeof(a)/sizeof(int);

    cout << *(a+1);
    cout << "原始数据:" << endl;
    for(int i = 0; i <len; ++i )
        cout << a[i] <<"、";
    cout << endl;

    qSort(a, 0, len-1);

    cout << "快排后数据:" << endl;
    for(int i = 0; i <len; ++i )
        cout << a[i] <<"、";
}


template <class T>
void qSort(T *a, int left, int right){
    const int len = right;
    while(left < right){
        while( *(a+left) < *(a+right) && left < right ) --right;
        // 以输入队列的第一个数为Key,自右向左寻找比key小的数,当前数不比key小则--right
        sW(a+left, a+right);
        while( *(a+left) < *(a+right) && left < right ) ++left;
        // 从左向右找比key大的数,找到后交换
        sW(a+left, a+right);
        qSort(a, 0, left-1);
        qSort(a, left+1, len);
    }
}

template <class T>
void sW(T *a, T *b){
    T temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

猜你喜欢

转载自www.cnblogs.com/TTYF/p/9108013.html
今日推荐