归并排序
归并排序,用C++实现,归并排序与堆排序时间复杂度都是O(NlogN)
1 /************************************************************************/ 2 /* 归并排序 3 /* 最大时间复杂度O(NlogN) 4 /************************************************************************/ 5 #include <stdio.h> 6 7 void Merge(int* array, int * tmpArray, int left, int center, int right) 8 { 9 int LeftCount = left; 10 int RightCount = center + 1; 11 int i = 0; 12 int NumElement = right - left + 1; 13 14 //依次从两个数组中取元素 15 while (LeftCount <= center && RightCount <= right) 16 { 17 if (array[LeftCount] < array[RightCount]) 18 { 19 tmpArray[i++] = array[LeftCount++]; 20 } 21 else 22 { 23 tmpArray[i++] = array[RightCount++]; 24 } 25 } 26 27 //将剩余的元素放入临时数组 28 if (LeftCount <= center) 29 { 30 while (LeftCount <= center) 31 { 32 tmpArray[i++] = array[LeftCount++]; 33 } 34 } 35 else 36 { 37 while (RightCount <= right) 38 { 39 tmpArray[i++] = array[RightCount++]; 40 } 41 } 42 43 //将元素从零时数组拷贝至原数组 44 for (int j = 0; j < NumElement ;) 45 { 46 array[left++] = tmpArray[j++]; 47 } 48 } 49 50 void MergeSort(int* array, int *tmpArray, int left, int right) 51 { 52 int center = (right + left) / 2; 53 if (left < right) 54 { 55 MergeSort(array, tmpArray, left, center); 56 MergeSort(array, tmpArray, center + 1, right); 57 Merge(array, tmpArray, left, center, right); 58 } 59 } 60 61 int main() 62 { 63 int array[10] = {10, 45, 78, 32, 89, 18, 105, 953, 243, 19}; 64 int* temp = new int[10]; 65 MergeSort(array, temp, 0, 9); 66 int i = 0; 67 int j = sizeof(array) / sizeof(int); 68 while (i < j) 69 { 70 printf("%d ", array[i++]); 71 } 72 return 0; 73 }