c_cpp 合并数组排序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 合并数组排序相关的知识,希望对你有一定的参考价值。

#include <iostream>
#include <vector>
using namespace std;

// merge left and right half of A into B, then assign all items in B into A
// left half range: [low, m], right half range: [m+1, high]
int merge(int A[], int low, int m, int high) {  // note, there is a 'm' parameter denoting for middle index
    int i = low, j = m+1, k = low;
    int B[500];                 // gist, temporary array
    
    while(i <= m && j <= high) {
        if(A[i] < A[j]) 
            B[k++] = A[i++];
        else
            B[k++] = A[j++];
    }
    
    while(i <= m) 
        B[k++] = A[i++];
    while(j <= high) 
        B[k++] = A[j++];
    k--;                        // gist
    
    for(int t=low; t<=high; t++)
        A[t] = B[t];
}

void merge_sort(int A[], int low, int high) {
    if(low >= high) return;
    int m = (low + high) >> 1;
    merge_sort(A, low, m);
    merge_sort(A, m+1, high);
    merge(A, low, m, high);
}

int main()
{
    int A[] = {3,4,9,2,1};
    merge_sort(A, 0, 4);
    for(int i=0; i<5; i++) cout << A[i] << " ";
    return 0;
}



以上是关于c_cpp 合并数组排序的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 合并排序

c_cpp 合并排序

c_cpp 合并排序

c_cpp 合并排序

c_cpp 合并排序

c_cpp 21.合并两个排序列表