Merge Sort

The basic idea of Merge Sort can be outlined as follows:

1. Check to see if the vector is empty or has only one element. If so, it must already be sorted, and the function can return without doing any work. This condition defines the simple case for the recursion.

2. Divide the vector into two smaller vectors, each of which is half the size of the original.

3. Sort each of the smaller vectors recursively.

4. Clear the original vector so that it is again empty.

5. Merge the two sorted vectors back into the original one.



/*
 * MergeSort.cpp
 *
 *  Created on: Feb 12, 2013
 *      Author: Steven.X.Wang
 */

#include <vector>

using namespace std;
/*
 * Function: Sort
 * --------------
 * This function sorts the elements of the vector into
 * increasing numerical order using the merge sort algorithm,
 * which consists of the following steps:
 *
 * 1. Divide the vector into two halves.
 * 2. Sort each of these smaller vectors recursively.
 * 3. Merge the two vectors back into the original one.
 */

void sort(vector<int> &v) {
	int n = v.size();
	if (n <= 1)
		return;

	vector<int> left, right;

	for (unsigned i = 0; i < n; i++) {
		if (i < n / 2)
			left.push_back(v[i]);
		else
			right.push_back(v[i]);
	}

	sort(left);
	sort(right);
	v.clear();
	merge(v, left, right);
}

/*
* Function: Merge
* ---------------
* This function merges two sorted vectors (v1 and v2) into the
* vector vec, which should be empty before this operation.
* Because the input vectors are sorted, the implementation can
* always select the first unused element in one of the input
* vectors to fill the next position.
*/
void merge(vector<int> &v, vector<int> &left, vector<int> &right) {
	unsigned leftPt = 0, rightPt = 0;

	while (leftPt < left.size() && rightPt < right.size()) {
		if (left[leftPt] < right[rightPt]) {
			v.push_back(left[leftPt++]);
		} else {
			v.push_back(right[rightPt++]);
		}
	}

	while(leftPt < left.size())
		v.push_back(left[leftPt++]);
	while(rightPt < right.size())
		v.push_back(right[rightPt++]);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值