归并排序

// test.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;

vector<int> remerge(vector<int> left, vector<int> right) {
	vector<int> res;
	vector<int>::iterator itleft= left.begin();
	vector<int>::iterator itright = right.begin();
	while (itleft!=left.end()&&itright!=right.end()) {
		if (*itleft<*itright) {
			res.push_back(*itleft);
			itleft++;
		}
		else {
			res.push_back(*itright);
			itright++;
		}
	}
	while (itleft != left.end()) {
		res.push_back(*itleft);
		itleft++;
	}
	while (itright != right.end()) {
		res.push_back(*itright);
		itright++;
	}
	return res;
}

vector<int> mergesort(vector<int> vec) {
	int size = vec.size();
	if (size <= 1) {
		return vec;
	}
	vector<int>::iterator mid = vec.begin() + size / 2;
	vector<int> left(vec.begin(), mid);
	vector<int> right(mid, vec.end());
	vector<int> mergeleft=mergesort(left);
	vector<int> mergeright=mergesort(right);
	return remerge(mergeleft, mergeright);
}

int main() {
	int a[] = { 2,1,8,6,3,9,3,5 };
	vector<int> vec(begin(a), end(a));
	vec=mergesort(vec);
	for (auto i : vec)
		cout << i << ",";
	cout << endl;
	
	system("pause");
	return 0;
}


©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页