qsort

  qosrt的这种写法,很简单,也很好理解。

  一开始没看懂,因为这一句swap(v, left, (left + right)/2); 后来转念一想,不是把left当成分割点,而是把(left+right)/2当分割点,恍然大悟。

  代码如下:

#include <stdio.h>

void swap(int v[], int i, int j) {
    int t = v[i];
    v[i] = v[j];
    v[j] = t;
}

void qsort(int v[], int left, int right) {
    int i, last;

    if(left >= right)
        return ;
    swap(v, left, (left+right)/2);
    last = left;
    for (i = left+1; i<=right; i++)
        if (v[i] < v[left])
            swap (v, ++last, i);
    swap(v, left, last);
    qsort(v, left, last-1);
    qsort(v, last+1, right);
}

int main(){
 //  int a[] = {-1, 32, 5, 1, 4}, i;
    int a[] = {32, -1, 5, 1, 4}, i;

    qsort(a, 0, 4);

    for (i=0; i<=4; i++) {
        printf("%d ", a[i]);
    }

    putchar('\n');

    return 0;
}

 

posted on 2013-08-07 20:58  Still_Raining  阅读(225)  评论(0编辑  收藏  举报