Merge Sort

来源:互联网 发布:js三级联动菜单 编辑:程序博客网 时间:2024/05/20 03:36

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.

/** 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> &vec) {int n = vec.size();if(n <= 1) return;   // already sortedvector<int> v1, v2;int i = 0;while(i < n) {if(i < n/2) {v1.push_back(vec[i++]);} else {v2.push_back(vec[i++]);}}Sort(v1);Sort(v2);vec.clear();Merge(vec, v1, v2);}/** 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> &vec, vector<int> &v1, vector<int> &v2) {int n1 = v1.size();int n2 = v2.size();int p1 = 0;int p2 = 0;while(p1 < n1 && p2 < n2) {if(v1[p1] <= v2[p2]) {vec.push_back(v1[p1++]);} else {vec.push_back(v2[p2++]);}}while(p1 < n1) vec.push_back(v1[p1++]);while(p2 < n2) vec.push_back(v2[p2++]);}


原创粉丝点击