码迷,mamicode.com
首页 > 其他好文 > 详细

Quick-sort

时间:2014-10-01 01:21:50      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   for   sp   div   

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 ;
}

 

Quick-sort

标签:style   blog   color   io   os   ar   for   sp   div   

原文地址:http://www.cnblogs.com/memoryh/p/4002837.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!