c_cpp 合并排序

Posted

tags:

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

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


 void print(int *a, int num) {
     
     for (int i = 0; i < num; i++) {
         cout << " " << a[i];
     }
     
     cout << endl;
     
 }

void merge(int* a, int left, int right) {
    int mid = (left + right)/2;
    
    int i1 = 0;
    int i2 = left;
    int i3 = mid +1;
    
    int temp [right - left + 1];
    
    cout << "merge: " << left << " " << right << endl; 
    
    while (i2 <= mid && i3 <= right) {
        
        if (a[i2] < a[i3]) {
            temp[i1++] = a[i2++];
        } else {
            temp[i1++] = a[i3++];
        }
    }
    
    
    while (i2 <= mid) {
        temp[i1++] = a[i2++];
    }
    
    while (i3 <= right) {
        temp[i1++] = a[i3++]; 
    }
    
    
    for (int i = left; i<= right; i++ ) {
        a[i] = temp[i - left];
        cout << "a[" << i << "]= " << a[i] << endl;
        
    }
    
}


 void merge_sort(int* a, int left, int right) {
     if (left < right) {
         
        cout << "merge_sort:" << left << " " << right << endl; 
        int mid = (right + left)/2;
        merge_sort(a, left, mid);
         
        cout << "pass:" << left << " " << right << endl; 
        merge_sort(a, mid+1, right);
        merge(a, left, right); 
     } else {
         cout << "skip: " << left << " " << right << endl;
    }
 }
  



int main() {
    
    const int num = 10;
    int arr[10] = { 10, 3, 2, 5, 4, 9, 8, 6 ,7, 1 };
    
    print(arr, num);
    
    merge_sort(arr, 0, 3);
    
    print(arr, num);
    
    
    return 0;
}

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

c_cpp 合并排序

c_cpp 合并排序

c_cpp 合并排序

c_cpp 合并排序

c_cpp 合并数组排序

c_cpp 21.合并两个排序列表