import random
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
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;
}