Chinaunix首页 | 论坛 | 博客
  • 博客访问: 26751
  • 博文数量: 41
  • 博客积分: 185
  • 博客等级: 入伍新兵
  • 技术积分: 260
  • 用 户 组: 普通用户
  • 注册时间: 2012-12-20 13:48
文章分类

全部博文(41)

文章存档

2013年(20)

2012年(21)

我的朋友
最近访客

分类:

2013-01-04 13:58:29

这是基于快速排序算法的C源代码,对于那些正在找工作的dd、mm们是很有帮助的,特将其共享与此,以求与你共奋进!


void swap(int *A, int *B) {
    
    int tmp = *A;

    *A = *B;
    *B = tmp;

}

void print(int *arr, int n) {
    
    int i = 0;
    
    for (;i < n;i++)
        printf("%d ", arr[i]);

    puts("");
}

/* first: we should get the larger number from
 * the two numbers which are the first differnt
 * from each other, when we scan the arr array
 * from left to right */


/* error: return -1
 * other: return the index of array
 * */

void findpivot(int left, int right, int *arr, int *ret) {

    int pos = left;
    int first = arr[left++];

    *ret = -1;
    
    while(left <= right) {
        if (first < arr[left]) {
            *ret = left;
            return ;
        } else if (first > arr[left]) {
            *ret = pos;
         return ;    
        }
        left++;
    }

}

/* return the left bound of right array of partition */
void partition(int left, int right, int *arr, int key, int *ret_pos) {

    int l = left;
    int r = right;

    do {
        swap(&arr[l], &arr[r]);

        while (arr[l] < key)
            l++;
        
        while (arr[r] >= key)
            r--;

    } while(l != r+1);

    *ret_pos = l;

}

void q_sort(int left, int right, int *array) {
    
    int pos;
    int lright;

    findpivot(left, right, array, &pos);

    if (pos < 0) return ;

    partition(left, right, array, array[pos], &lright);

    q_sort(left, lright-1, array);

    q_sort(lright, right, array);

}

void quick_sort(int *arr, int n) {

    q_sort(0, n-1, arr);

}


完整的程序可以在这里下载:
文件:quick-sort.c.tar.gz
大小:1KB
下载:下载
阅读(88) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~