美文网首页
MERGE SORT

MERGE SORT

作者: larrymusk | 来源:发表于2017-11-27 17:27 被阅读0次
    void merge(int a[], int m, int b[], int n)
    {
            int len = m+n-1;
            m = m-1;
            n = n-1;
            int * buffer = calloc(len+1, sizeof(int));
            int buffer_length = len+1;
            for(int i = 0; i < m+1;i++)
                    buffer[i] = a[i];
            while(m>=0 && n>=0){
                    if(a[m] < b[n])
                            buffer[len--] = b[n--];
                    else
                            buffer[len--] = a[m--];
    
            }
    
            while(n >= 0){
                    buffer[len--] = b[n--];
            }
    
            for(int i = 0; i < buffer_length;i++)
                    a[i] = buffer[i];
    
            free(buffer);
    }
    
    void merge_sort(int a[], int len)
    {
            if(len == 0 || len ==1)
                    return;
    
            int mid = (len-1)/2;
    
            merge_sort(a, mid+1);
            merge_sort(a+mid+1,len-mid-1);
    
            merge(a, mid+1, a+mid+1, len-mid-1);
    
    }
    

    相关文章

      网友评论

          本文标题:MERGE SORT

          本文链接:https://www.haomeiwen.com/subject/lmvdbxtx.html