递归的归并排序
// MergeSorttest.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <VECTOR> #include <IOSTREAM> using namespace std; void Merge(vector<int> & v,int begin,int mid,int end){ int i = 0; vector<int> temp; int index1 = begin; int index2 = mid+1; while(index1 <= mid && index2 <= end){ if(v[index1] < v[index2]){ temp.push_back(v[index1]); index1++; } else{ temp.push_back(v[index2]); index2++; } } while(index1 <= mid) temp.push_back(v[index1++]); while(index2 <= end) temp.push_back(v[index2++]); for(i = 0;i<temp.size();i++){ // cout<<temp[i]<<" "; v[begin++] = temp[i]; } } void MergeSort(vector<int> & v,int begin,int end){ if(begin < end){ int mid = (begin+end)/2; MergeSort(v,begin,mid); MergeSort(v,mid+1,end); Merge(v,begin,mid,end); } } int main(int argc, char* argv[]) { int array[] = {2,1,86,36,96,47,41,42,36,61,46,98,63,71,8,0,111,42,111,122,756,245,176,786 }; vector<int> ivec(array,array+sizeof(array)/sizeof(int)); MergeSort(ivec,0,sizeof(array)/sizeof(int)-1); for(int i = 0;i<sizeof(array)/sizeof(int);i++) cout<<ivec[i]<<" "; cout<<endl; return 0; }