算法笔记 --- Merge Sort

#include <iostream>

using namespace std;
class MergeSort {
public:
    int* mergeSort(int* A, int n) {
        mergeSortRecursive(A, 0, n);
        return A;
    }
    void mergeSortRecursive(int* A, int index_beg, int index_end){
        if(index_end - index_beg > 1){
            int median = (index_beg + index_end)/2;
            mergeSortRecursive(A, index_beg, median);
            mergeSortRecursive(A, median, index_end);
            merge(A, index_beg, median, index_end);
        }
    }
    void merge(int* A, int index_beg, int median, int index_end){
        int index1 = index_beg;
        int index2 = median;
        int sort_tmp[100];
        int index_tmp = 0;
        while(index1 < median && index2 < index_end){
            if(A[index1] < A[index2]){
                sort_tmp[index_tmp++] = A[index1++];
            }else{
                sort_tmp[index_tmp++] = A[index2++];
            }
        }
        while(index1 < median)
            sort_tmp[index_tmp++] = A[index1++];
        while(index2 < index_end)
            sort_tmp[index_tmp++] = A[index2++];
        for(int i = index_beg; i < index_end; i++){
            A[i] = sort_tmp[i - index_beg];
        }
    }
};
int main()
{
    int a[6] = {1, 5, 7, 2, 9, 4};
    int* res;
    MergeSort sorter;
    res = sorter.mergeSort(a, 6);
    cout<<"after sorting:"<<endl;
    for(int i = 0; i < 6; i++){
        cout<<res[i]<<" ";
    }
    cout<<endl;
   
    return 0;
}

 

转载于:https://www.cnblogs.com/zhongzhiqiang/p/5791086.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值