1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| void Merge_Sort(ElementType A[],int N) { int length = 1; ElementType * tempA; tempA = new ElementType[N]; if(tempA != nullptr) { while(length < N) { Merge_pass(A,tempA,N,length); length *= 2; Merge_pass(tempA,A,N,length); length *= 2; } delete [] tempA; } else { std::cout<<"error"<<std::endl; } }
void Merge_pass(ElementType A,ElementType tempA,int N,int length) { for(i = 0;i <= N - 2*length;i += 2*length) { Merge_(A,tempA,i,i+length,i+2*length - 1); } if(i+legnth < N) { Merge_(A,tempA,i,i+length,N - 1); } else { for(j = i; j < N;j++) { tempA[j] = A[j]; } } }
void Merge_(ElementType A[],ElementType tempA[],int L,int R,int RightEnd) { leftEnd = R - 1 temp_index = L; NumElements = RightEnd - L + 1;
while(L <= LeftEnd && R <= RightEnd) { if(A[L] < A[R]) { tempA[temp_index++] = A[L++]; } else { tempA[temp_index++] = A[R++]; } } while(L <= LeftEnd) { tempA[temp_index++] = A[L++]; } while(R <= RightEnd) { tempA[temp_index++] = A[R++]; } }
|