Code implementation c6>
#include"stdafx.h"#include<iostream>#include<ctime>using namespacestd;inta[1000000];inttempa[1000000];#defineBegin_record \{clock_t ____temp_begin_time___; ____temp_begin_time___=clock ();#defineEnd_record (dtime) \Dtime=float(Clock ()-____temp_begin_time___)/clocks_per_sec;}/*merge Sort merging process A-pending array L-Sort area left border M-sort area midpoint R-Sort area right border*/voidMergeintA[],intLintMintR) { inti =l; intj = m+1; intK; //int tempa[100000]; //space complexity O (n), where n temporary storage space is required for the last merge//merge two ordered regions into an ordered region//Part1: Both of the sorted regions are compared from index n (0,1...N), the smaller value is push into the temporary array, and the sort region compares the index +1; When the value of any sort area is exhausted, the end part1 for(k = l; I <= M && J <= R; k++) { if(A[i] <=A[j]) {Tempa[k]= a[i++]; } Else{Tempa[k]= a[j++]; } } //Part2: The remaining value of another sort area is pressed into the temporary array in an orderly push. At this point the temporary array is a merged ordered region. End Part2 if(I <=m) for(; k <= R; k++) Tempa[k]= a[i++]; if(J <=R) for(; k <= R; k++) Tempa[k]= a[j++]; //Part3: Copies the temporary array data to the original array. Sort End for(intK = l; K <= R; k++) {A[k]=Tempa[k]; }}/** Merge sort time complexity O (N*LOGN), Spatial complexity O (n) in the case of the need for stable ordering, the merge sort is the most without considering the stability of the case, the merge sort due to the need O (n) temporary storage space, compared to the memory, the effect is not as fast as sorting */voidMergeSort (intA[],intLintR) { intm; if(L <r) {m= (L + r)/2; //recursive decomposition process, subdivision area until the number of elements per region is less than or equal to 2MergeSort (A, L, M-1); MergeSort (A, M+1, R); //merge Processmerge (A, L, M, R); }}voidPrintArray (intA[],intlength) {cout<<"Array Contents:"; for(inti =0; i < length; i++) { if(i = =0) cout<<A[i]; Elsecout<<","<<A[i]; } cout<<Endl;}int_tmain (intARGC, _tchar*argv[]) { floatTim; for(inti =0; I <1000000; i++) {A[i]=int(rand ()%100000); } Begin_record//PrintArray (A, sizeof (a)/sizeof (int.));MergeSort (A,0,sizeof(a)/sizeof(int)-1); //PrintArray (A, sizeof (a)/sizeof (int.));End_record (Tim) cout<<"Run Time:"<< Tim <<"s"<<Endl; System ("Pause"); return 0;}