Native/C

merge sort

aucd29 2013. 10. 2. 18:46
[code]#include <stdio.h>
#include <assert.h>
#include <stdlib.h>

//
// 2, 4, 6, 8 식으로 정렬하게 됨
//


//
// Function
//
void merge(int a[], int b[], int c[], int m, int n);
void mergesort(int key[], int n);
void wrt(int key[], int sz);

int main(int argc, char *argv[])
{
    int sz, key[] = {4, 3, 1, 67, 55, 8, 0, 4, -5, 37, 7, 4, 2, 9, 1, -1};

    sz = sizeof(key) / sizeof(int);
    printf("Before mergesort : \n");
    wrt(key,sz);
    mergesort(key,sz);
    printf("After mergesort : \n");
//    wrt(key,sz);
    return 0;
}

void wrt(int key[], int sz)
{
    int i;
    for(i=0;i<sz;++i)
    {
        printf("%4d%s", key[i], ((i<sz-1)?"":"\n"));
    }
}

void merge(int a[], int b[], int c[], int m, int n)
{
    int i=0, j=0, k=0;

    while(i < m && j <n)
    {
        printf("A:%d, B:%d \n", a[i],b[j]);
        if(a[i] < b[j])
        {            
            c[k++] = a[i++];
        }
        else
        {
            c[k++] = b[j++];
        }
    }

    while(i < m)            // 비교된것이 없으면 걍 들어간다.
    {
        c[k++] = a[i++];
    }

    while(j < n)
    {
        c[k++] = b[j++];
    }
}

void mergesort(int key[], int n)
{
    int j,k,m,*w;
    for(m=1;m<n;m*=2)
        ;
    if(n < m)
    {
        printf("ERROR : Array size is not a power of 2 - bye!\n");
        exit(1);
    }

    w = calloc(n, sizeof(int));
    assert(w != NULL);
    for(k=1;k<n;k*=2)
    {
        for(j=0;j<n-k;j+=2*k)
        {
            //
            // Merge two subarrsy of *key into a subarray of *w;
            //
            merge(key+j, key+j+k, w+j, k, k);
        }
        //printf("\n=================\n");
        for(j=0;j<n;++j)
        {
            key[j] = w[j];
        }
        wrt(key,n);
    }
    free(w);
}    [/code]