C++快排实现代码

/*

quick sort src code

*/

#include

#include
#include
#include


#define PRINT_FLAG 0 //用于调试,为1时打印过程与结果输出
using namespace std;


//create an index within the range start to over
int RandInRange(int start,int over){
    int len = over - start;
    return start+rand()%len;
}


//swap two integers
void swap_num(int &a,int &b){
    int tmp = b;
    b = a;
    a = tmp;
}


//  print number array
void print_num(int n[],int len){
    int i = 0;
    while(i         cout << n[i] << " ";
        i++;
    }
    cout << endl << "------------------" << endl;
}


void quickSort(int *num,int len,int start,int stop){


    // error return
    if(start >= stop || len <= 0 || start < 0 || (stop - start) >= len)
        return;
    // set an index and put it to the end
    int index = RandInRange(start,stop);
    swap_num(num[index],num[stop]);
    int i = start;
    int j = stop - 1;


    // find the correct position if the index above
    while(j > i){
        while(num[i] <= num[stop] && i < stop)
            i++;
        while(num[j] > num[stop] && j > start)
            j--;
        if(i > j)
            break;
        swap_num(num[i],num[j]);
    }


    if(i < stop)
        swap_num(num[i],num[stop]);
#if PRINT_FLAG
    print_num(num,10);
#endif // PRINT_FLAG
    quickSort(num,i,start,i-1);
    quickSort(num,len - i -1,i+1,stop);
}


int main()
{
    int a[10] = {0,5,1,4,7,8,6,9,3,2};
    srand ( time(NULL) );
    quickSort(a,10,0,9);
#if PRINT_FLAG
    print_num(a,10);
#endif // PRINT_FLAG
    return 0;
}

你可能感兴趣的:(C++)