Quick-sort

brief : the quick sort can divide into two steps, the first step is partition, the second step is conquer the subset.

i) as the first step, array A[left, right], we choose the first element as a pivot, and two index i and j  which initialized as left+1, and i is a bondary index which A[left, i-1] < pivot and A[i, j] >= pivot.  then loop from j to right, if A[j] greater-equal than pivot which is we expected, do nothing just increase index j, otherwise  we swap A[i-1] (the latest one which less than pivot) and A[j], and increase ++i, ++j . after the loop, we get array A[left+1, i-1] < pivot, A[i, right] >= pivot, at last we swap A[left] and A[i-1];  

2) conquer the subset , after the first operation, A[left, i-2] < pivot, A[i-1] = pivot, A[i, right] >= pivot, just do the first step to the subset;

 

code:

void quick_sort(char* p, int left, int right)

{

    int i , j, pivot ;

    if(left >= right)

       return;      

    pivot = p[left];

    for(i=j=left+1; j <=right; ++j)

    {

          if(p[j] < pivot)

              swap(p[i++], p[j]);

    }    

    swap(p[left], p[i-1]) ;

    quick_sort(p, left, i-2) ;

    quick_sort(p, i, right);        

    return ;

}

 

你可能感兴趣的:(sort)