排序算法 之 归并排序
1 #include <iostream> 2 using namespace std; 3 4 int merge(int data[],int length,int start, int end) 5 { 6 if (data == nullptr || length <= 0 || length <= end) 7 { 8 return 0; 9 } 10 int middle = (start + end)>>1; 11 int *NewData = new int[length]; 12 13 int len = start; 14 int i = start ,j = middle+1; 15 while ( i <= middle && j <= end) 16 { 17 if (data[i] < data[j]) 18 { 19 NewData[len++] = data[i]; 20 i ++; 21 } 22 else 23 { 24 NewData[len++] = data[j]; 25 j ++; 26 } 27 } 28 while ( i <= middle) 29 { 30 NewData[len++] = data[i++]; 31 } 32 while ( j <= end) 33 { 34 NewData[len++] = data[j++]; 35 } 36 for (int i = start; i <= end ;i++) 37 { 38 data[i] = NewData[i]; 39 } 40 delete NewData; 41 NewData = nullptr; 42 } 43 int mergeSort(int data[],int length,int start, int end) 44 { 45 if (data == nullptr || length <= 0 || length <= end) 46 { 47 return 0; 48 } 49 int middle = (start + end )>> 1; 50 if (start == end) 51 { 52 return 0; 53 } 54 if(start < end) 55 { 56 mergeSort(data,length,start,middle); 57 mergeSort(data,length,middle+1,end); 58 merge(data,length,start,end); 59 for (int i =0 ;i < length ;++i) 60 { 61 printf("%d ",data[i]); 62 } 63 printf("\n"); 64 } 65 } 66 int main() 67 { 68 int data[] = {2,5,1,4,0,-3,59,-78,62,3}; 69 mergeSort(data,sizeof(data)/sizeof(int),0,sizeof(data)/sizeof(int)-1); 70 printf("\n\n"); 71 for (int i =0 ;i < sizeof(data)/sizeof(int) ;++i) 72 { 73 printf("%d ",data[i]); 74 } 75 printf("\n"); 76 return 0; 77 }
输出结果为:
2 5 1 4 0 -3 59 -78 62 3
1 2 5 4 0 -3 59 -78 62 3
1 2 5 0 4 -3 59 -78 62 3
0 1 2 4 5 -3 59 -78 62 3
0 1 2 4 5 -3 59 -78 62 3
0 1 2 4 5 -78 -3 59 62 3
0 1 2 4 5 -78 -3 59 3 62
0 1 2 4 5 -78 -3 3 59 62
-78 -3 0 1 2 3 4 5 59 62
1 2 5 4 0 -3 59 -78 62 3
1 2 5 0 4 -3 59 -78 62 3
0 1 2 4 5 -3 59 -78 62 3
0 1 2 4 5 -3 59 -78 62 3
0 1 2 4 5 -78 -3 59 62 3
0 1 2 4 5 -78 -3 59 3 62
0 1 2 4 5 -78 -3 3 59 62
-78 -3 0 1 2 3 4 5 59 62
-78 -3 0 1 2 3 4 5 59 62
请按任意键继续. . .
To get,you have to give.To give,you need learn to insist.If you really find it is hard for you,then you quit.But once you quit.Don't complain.