标签:style blog class code java color
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 void MerageSort(int *A, int low, int high); 5 void Merge(int *A, int low, int middle, int high); 6 7 int main() 8 { 9 10 int array[] = {2, 3, 6, 5, 4, 3, 3}; 11 int low = 0, high = 7; 12 13 int i = 0; 14 for(i = low; i < high; i++) 15 { 16 printf("%d ", array[i]); 17 } 18 printf("\n"); 19 20 MerageSort(array, low, high - 1); 21 22 23 system("pause"); 24 return 0; 25 } 26 27 void Merge(int *A, int low, int middle, int high) 28 { 29 int i = low, j = middle + 1; 30 int m = middle, n = high; 31 int k = 0; 32 int *A1 = (int*)malloc((high - low + 1)*sizeof(int)); 33 printf("low = %d, middle = %d, high = %d\n", low, middle, high); 34 35 while(i <= m && j <= n) 36 { 37 if(A[i] < A[j]) 38 { 39 A1[k] = A[i]; 40 i++; 41 } 42 else 43 { 44 A1[k] = A[j]; 45 j++; 46 } 47 k++; 48 } 49 50 while(i <= m) //加到尾部 51 { 52 A1[k] = A[i]; 53 k++; 54 i++; 55 } 56 57 while(j <= n) //加到尾部 58 { 59 A1[k] = A[j]; 60 k++; 61 j++; 62 } 63 64 for(i = 0; i < high -low + 1; i++) 65 { 66 A[low + i] = A1[i]; 67 printf("%d ", A[low + i]); 68 } 69 printf("\n"); 70 71 free(A1); 72 A1 = NULL; 73 } 74 75 76 void MerageSort(int *A, int low, int high) 77 { 78 int middle = 0; 79 if(low < high) 80 { 81 middle = (low + high)/2; 82 MerageSort(A, low, middle); 83 MerageSort(A, middle+1, high); 84 Merge(A, low, middle, high); 85 86 } 87 }
运行结果:
标签:style blog class code java color
原文地址:http://www.cnblogs.com/hdu-2010/p/3706170.html