Merge sort

pseudocode:

MERGE-SORTA[1 . . n]
1.If n= 1, done.
2.Recursively sort A[ 1 . . ⎡n/2⎤]and A[ ⎡n/2⎤+1 . . n ] .
3.Merge”the 2sorted lists.

C++:

const int N = 100;
void merge(int * a,int lhs,int mid,int rhs) {
    int b[N];
    int p1 = lhs;    //数组1下标
    int p2 = mid + 1; //数组2下标
    int p3 = 0;  //b[] 下标
    while (p1 <= mid && p2 <= rhs) {
        if (a[p1] <= a[p2]) {
            b[p3] = a[p1];
            ++p1;
            ++p3;
        }
        else {
            b[p3] = a[p2];
            ++p2;
            ++p3;
        }
    }
    if (p1 <= mid) {
        for (;  p1<= mid; ++p1) {
            b[p3] = a[p1];
            ++p3;
        }
    }
    else {
        for (; p2 <= rhs; ++p2) {
            b[p3] = a[p2];
            ++p3;
        }
    }
    for (int i = lhs, j = 0 ; i <= rhs; ++i,++j) {
        a[i] = b[j];
    }
}

void MergeSort(int * a,int lhs,int rhs) {
    if (lhs < rhs) {
        int mid = (lhs + rhs) / 2;
        MergeSort(a, lhs, mid);
        MergeSort(a, mid + 1, rhs);
        merge(a, lhs, mid , rhs);
    }
}

Text:

#include<iostream>
const int N = 100;
void merge(int * a,int lhs,int mid,int rhs) {
    int b[N];
    int p1 = lhs;    //数组1下标
    int p2 = mid + 1; //数组2下标
    int p3 = 0;  //b[] 下标
    while (p1 <= mid && p2 <= rhs) {
        if (a[p1] <= a[p2]) {
            b[p3] = a[p1];
            ++p1;
            ++p3;
        }
        else {
            b[p3] = a[p2];
            ++p2;
            ++p3;
        }
    }
    if (p1 <= mid) {
        for (;  p1<= mid; ++p1) {
            b[p3] = a[p1];
            ++p3;
        }
    }
    else {
        for (; p2 <= rhs; ++p2) {
            b[p3] = a[p2];
            ++p3;
        }
    }
    for (int i = lhs, j = 0 ; i <= rhs; ++i,++j) {
        a[i] = b[j];
    }
}

void MergeSort(int * a,int lhs,int rhs) {
    if (lhs < rhs) {
        int mid = (lhs + rhs) / 2;
        MergeSort(a, lhs, mid);
        MergeSort(a, mid + 1, rhs);
        merge(a, lhs, mid , rhs);
    }
}

int main() {
    int a[11] = { 10,9,8,7,6,5,4,3,2,1,0 };
    MergeSort(a, 0,10);
    for (auto c : a) {
        std::cout << c << std::endl;
    }


    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值