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++]);}
- Merge Sort
- Merge sort
- merge sort
- merge sort
- merge sort
- Merge Sort
- merge sort
- Merge Sort
- Merge Sort
- merge sort
- Merge Sort
- Merge sort
- Merge-sort
- Merge Sort
- Merge sort
- Merge Sort
- Merge-Sort
- merge sort
- 定时任务组件使用经验介绍
- 【Windows】查看电脑的开关机时间
- dijkstra算法--刚学
- 表信息重复处理
- left join条件写在on中和where中的区别
- Merge Sort
- ubuntu10.10嵌入式boa web服务器移植
- 网络推广员的苦恼
- Android中怎么让你的layout适应屏幕的大小
- 【Windows】虚拟内存设置
- unicode UTF-8 GBK GB2312 之间的区别和关系
- 【Windows】Windows7下游戏全屏问题通用解决方法
- 仿腾讯QQ界面
- SQL语句提高性能