bon

  C++博客 :: 首页 :: 联系 :: 聚合  :: 管理
  46 Posts :: 0 Stories :: 12 Comments :: 0 Trackbacks

常用链接

留言簿(2)

我参与的团队

搜索

  •  

最新评论

阅读排行榜

评论排行榜

Recently, I began to peruse the CLRS (Introduction to Algorithms).

Now I would like to scan all basic algorithms, especially sorting and searching.

Let me first present a classic sorting algorithm - merge sort. Here is my code. Before I reach here, some mistakes are made, thus I note these "pitfalls" in the code

#include <stdlib.h>
#include <stdio.h>
#define MAX 1e9    // the biggest possible value of a int number is 2^31 - 1 which is approximately 10^9
#define SIZE 10

int *a;
int *b;
int *c;

// merge [p, q] and [q+1, r], where within each range number are sorted
void merge(int p, int q, int r)
{
    int k;
    int length = r - p +1;            // the length the range to be merge
    for (k = 0; k < q - p + 1; k++) {
        b[k] = a[p + k];             // copy number in a[p, q] to b
    }
    b[k] = MAX;             // b[k] = MAX, not b[k+1]=MAX
    for (k = 0; k < r - q; k++) {
        c[k] = a[q + 1 + k];             // copy number in a[q+1, r] to c
    }
    c[k] = MAX;             // c[k] = MAX, not c[k+1]=MAX

    /* BEGIN merging */
    int i = 0;
    int j = 0;
    for (k=0;k<length;k++) {             // do exactly length times of copy
        if (b[i] < c[j]) {
            a[p + k] = b[i++];          // be careful! a[p, r] is a whole range now, and watch out the base "p"
        } else {
            a[p + k] = c[j++];
        }
    }
}

void merge_sort(int l, int u)
{
    if (l == u) return;             // when to stop recursion? only one number needs no sorting
    int m = (l + u)/2;
    merge_sort(l, m);
    merge_sort(m + 1, u);
    merge(l, m, u);
}

int main()
{
    a = (int*)malloc(SIZE * sizeof(int));
    b = (int*)malloc(SIZE * sizeof(int));          // cache, avoid many "malloc" in the merge function
    c = (int*)malloc(SIZE * sizeof(int));          // this trick is from "Programming Pearls"
    int i;
    for (i = 0; i < SIZE; i++) {
        a[i] = SIZE - i;
    }
    merge_sort(0, SIZE - 1);                    // watch out the range
    for (i = 0; i < SIZE; i++) {
        printf("%d\n", a[i]);
    }
    return 1;
}

posted on 2009-04-30 13:57 bon 阅读(225) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


Google PageRank 
Checker - Page Rank Calculator