1 #include "iostream" 2 #include "vector" 3 #include "time.h" 4 #include "iomanip" 5 using namespace std; 6 7 #define num 25 8 typedef int type;//type类型为int 9 10 /* 11 *将非降数组A,B,中的元素 12 */ 13 void merge(vector<type>A,vector<type>B,vector<type>&C,int flags) 14 { 15 int ia =0,ib=0,ic=0; 16 if(flags==1)//升序 17 { 18 while(ia<A.size()&&ib<B.size()) 19 { 20 if(A[ia]<=B[ib]) 21 { 22 C.push_back(A[ia++]); 23 }else C.push_back(B[ib++]); 24 } 25 }else if(flags==0){//降序 26 while(ia<A.size()&&ib<B.size()) 27 { 28 if(A[ia]>=B[ib]) 29 { 30 C.push_back(A[ia++]); 31 }else C.push_back(B[ib++]); 32 } 33 } 34 while(ia<A.size()) 35 { 36 C.push_back(A[ia++]); 37 } 38 39 while(ib<B.size()) 40 { 41 C.push_back(B[ib++]); 42 } 43 44 } 45 46 /* 47 *将n个长度的子表归并为m个子表(n为偶数,m=n/2;否,m=n/2+1) 48 */ 49 int Merge_sort(vector<vector<int>>array,int n,vector<vector<int>>&mid,int &count,int flags) 50 { 51 int i; 52 if(n%2==0) 53 { 54 count = n/2; 55 for(i=0;i<n-1;i=i+2) 56 { 57 merge(array[i],array[i+1],mid[i/2],flags); 58 } 59 }else{ 60 count = n/2 +1; 61 vector<int>temp; 62 temp.clear(); 63 for(i=0;i<n-2;i=i+2) 64 { 65 merge(array[i],array[i+1],mid[i/2],flags); 66 } 67 merge(array[n-1],temp,mid[count-1],flags); 68 } 69 return 0; 70 } 71 72 void Sort_Merge() 73 { 74 int i,j,flags; 75 time_t start,end; 76 vector<int>array; 77 cout<<"Initialize Array:"<<endl; 78 for(i=0;i<num;i++)//随机产生数组中的数据 79 { 80 array.push_back(rand()%1000); 81 cout<<setw(5)<<array[i]<<" "; 82 if((i+1)%10==0)cout<<endl; 83 } 84 cout<<endl; 85 cout<<"please inout flags[flags:1,升序;0降序]:"; 86 cin>>flags; 87 start = clock(); 88 vector<vector<int>>arraymid(array.size()); 89 for(i=0;i<array.size();i++)//初始化num个子表 90 { 91 arraymid[i].push_back(array[i]); 92 } 93 vector<vector<int>>mid(num);//存放num个子表归并后的子表 94 int count =arraymid.size();//用于记录起始子表数目 95 int countmid = count;//用于记录归并后子表的数目 96 while(count!=1) 97 { 98 for(i=0;i<countmid;i++) 99 { 100 mid[i].clear();//清空待存放归并后子表的数组 101 } 102 Merge_sort(arraymid,count,mid,countmid,flags);//归并 103 104 for(i=0;i<count;i++)//将归并后的子表赋给arraymid,然后继续归并 105 { 106 arraymid[i].clear(); 107 for(j=0;j<mid[i].size();j++) 108 { 109 arraymid[i].push_back(mid[i][j]); 110 } 111 } 112 count = countmid;//子表数目更新为归并后的子表数目 113 } 114 end = clock(); 115 cout<<"The Merge_Sorted Array:"<<endl; 116 //输出最终排序后的的结果 117 for(i=0;i<count;i++) 118 { 119 for(j=0;j<mid[i].size();j++) 120 { 121 cout<<setw(5)<<mid[i][j]<<" "; 122 if((j+1)%10==0)cout<<endl; 123 } 124 } 125 cout<<endl; 126 127 cout<<"performnace time:"; 128 cout<<(double)(end - start )/1000<<"Seconds"<<endl; 129 } 130 131 int main() 132 { 133 Sort_Merge(); 134 return 0; 135 }