归并排序-C++代码

作者: CharlesZhangCh | 来源:发表于2018-01-19 16:54 被阅读194次
    #include <iostream>
    
    void merge(int a[], int b[], int l, int m, int r)
    {
        int i = l;
        int j = m + 1;
        int k = l;
        
        while (k <= r) {
            if (i > m) {
                b[k++] = a[j++];
            }
            else if (j > r) {
                b[k++] = a[i++];
            }
            else {
                if (a[i] > a[j]) {
                    b[k++] = a[j++];
                }
                else {
                    b[k++] = a[i++];
                }
            }
        }
    
        for (int k = l; k <= r; k++) {
            a[k] = b[k];
        }
    }
    
    void merge_sort_helper(int a[], int b[], int l, int r)
    {
        if (l >= r) {
            return;
        }
        int m = (l + r)/2;
        merge_sort_helper(a, b, l, m);
        merge_sort_helper(a, b, m + 1, r);
        merge(a, b, l, m, r);
    }
    
    void merge_sort(int a[], int len)
    {
        int *b = new int[len];
        merge_sort_helper(a, b, 0, len - 1);
        delete[] b;
    }
    
    int main(int argc, const char * argv[])
    {
        int a[] = {1, 1, 6, 6, 8, 3, 5, 100, 300, 200, 99, 99};
        merge_sort(a, sizeof(a)/sizeof(a[0]));
    
        for (int i : a) {
            std::cout << i << ' ';
        }
        std::cout << std::endl;
        
        return 0;
    }
    
    

    相关文章

      网友评论

        本文标题:归并排序-C++代码

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