归并排序-Python and C++

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
#归并排序 mergeSort
# merge : 合并两个有序数组
def merge(left, right):
    result = []
    while left and right:
        if left[0] <= right[0]:
            result.append(left.pop(0))
        else:
            result.append(right.pop(0))
    while left:
        result.append(left.pop(0))
    while right:
        result.append(right.pop(0))
    return result
def mergeSort(arr):
    if len(arr) < 2:
        return arr
    middle  = len(arr) / 2  #py2: 5/2=2(5/2.=2.5); py3: 5/2=2.5(5//2=2)
    left, right = arr[:middle], arr[middle:]
    return merge(mergeSort(left), mergeSort(right))

if __name__ == "__main__":
    testList = [random.randint(0,99) for i in range(10)]
    print 'test list:', testList
    print 'after sort:', mergeSort(testList)
#include <vector>
#include <iostream>
#include <iterator>
#include <random>
using namespace std;
///合并两个有序数组
vector<int> merge(vector<int>& left, vector<int>& right)
{
    vector<int> result;
    while((left.size() > 0) && (right.size() > 0)) {
        if(left[0] <= right[0]) {
            result.push_back(left[0]);
            vector<int>::iterator k = left.begin();
            left.erase(k);
        }
        else {
            result.push_back(right[0]);
            vector<int>::iterator k = right.begin();
            right.erase(k);
        }
    }
    while(left.size() > 0) {
        result.push_back(left[0]);
        vector<int>::iterator k = left.begin();
        left.erase(k);
    }
    while(right.size() > 0) {
        result.push_back(right[0]);
        vector<int>::iterator k = right.begin();
        right.erase(k);
    }
    return result;
}
vector<int> mergeSort(vector<int>& arr)
{
    if(arr.size() < 2) return arr;
    int middle = arr.size() / 2;
    vector<int> left(arr.begin(), arr.begin() + middle);
    vector<int> right(arr.begin() + middle, arr.end());
    vector<int> sortLeft = mergeSort(left);
    vector<int> sortRight = mergeSort(right);
    return merge(sortLeft, sortRight);
}
int main()
{
    vector<int> testList;
    std::default_random_engine e;
    std::uniform_int_distribution<> u(0,99);
    for(int i = 0; i < 10; i++) {
        testList.push_back(u(e));
    }
    for(auto item : testList) {
        cout << "item:" << item << endl;
    }
    vector<int> afterSort = mergeSort(testList);
    for(auto item : afterSort) {
        cout << "after sort item:" << item << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值