一、用数组临时存储 #include <iostream> using namespace std; const int N = 5; int a[N]; void MergeSort(int left,int right); void Merge(int left,int mid,int right); void main() { int i; cout<<"Input "<< N <<" numbers please:"; for(i=0;i<N;i++) cin >> a[i]; MergeSort(0,N-1); cout << "The sorted array is" << endl; for(i=0;i<N;i++) cout << a[i] << " "; cin.get(); cin.get(); } void MergeSort(int left,int right) { int mid = 0; if(left < right){ mid = (left + right) / 2; MergeSort(left,mid); MergeSort(mid+1,right); Merge(left,mid,right); } } void Merge(int left,int mid,int right) { int i = left, j = mid + 1, k = left; int temp[N]; while( (i <= mid) && (j <= right) ){ if( a[i] <= a[j] ) temp[k++] = a[i++]; else temp[k++] = a[j++]; } for(int q=i; q <= (i>mid?right:mid); q++) temp[k++] = a[q]; for(i=left;i<=right;i++) a[i] = temp[i]; } 二、用数组模拟链表 #include <iostream> #include <ctime> #include <windows.h> using namespace std; const int N = 1000; int a[N+1],link[N+1]; void CreatRandomArray(int a[],int b[]); void PrintArray(int a[]); void PrintMerge(int i); int MergeSort(int left,int right); int Merge(int p,int q); void main() { int head; double t,ave[10]; LARGE_INTEGER begin,end,clocks; QueryPerformanceFrequency(&clocks); //每秒多少个clock for (int i=0;i<10;i++){ CreatRandomArray(a,link); //PrintArray(a); QueryPerformanceCounter(&begin); //计时开始 head = MergeSort(1,N); QueryPerformanceCounter(&end); //计时结束 //PrintMerge(head); t = (end.QuadPart-begin.QuadPart+0.0)/clocks.QuadPart; ave[i] = t; //cout << endl << "Totle time:"<< t << "sec" << endl; } t = 0; for (int i=0;i<10;i++) t += ave[i]; t /= 10; cout << endl << "The average time:"<< t << "sec" << endl; } int MergeSort(int left,int right) { int mid,p,q; if(left < right){ mid = (left + right) / 2; p = MergeSort(left,mid); q = MergeSort(mid+1,right); return Merge(p,q); } else return left; } int Merge(int p,int q) { int k = 0; while( (p != 0) && (q != 0) ){ if( a[p] <= a[q] ){ link[k] = p; k = p; p = link[p]; } else{ link[k] = q; k = q; q = link[q]; } } if ( p == 0 ) link[k] = q; else link[k] = p; return link[0]; } void CreatRandomArray(int a[],int link[]) { LARGE_INTEGER seed; QueryPerformanceCounter(&seed); srand(seed.QuadPart); for (int i=0;i<=N;i++){ a[i] = rand() % 10000; link[i] = 0; } } void PrintArray(int a[]) { cout << "The Random array is" << endl; for (int i=1;i<=N;i++) cout << a[i] <<" "; cout << endl << endl; } void PrintMerge(int i) { cout << "The MergeSorted array is" << endl; cout << a[i] << " "; while (link[i] != 0){ i = link[i]; cout << a[i] << " "; } }