码迷,mamicode.com
首页 > 其他好文 > 详细

归并排序(分治)

时间:2014-05-04 20:44:56      阅读:417      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   color   

bubuko.com,布布扣
 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 }
bubuko.com,布布扣

运行结果:

bubuko.com,布布扣

归并排序(分治),布布扣,bubuko.com

归并排序(分治)

标签:style   blog   class   code   java   color   

原文地址:http://www.cnblogs.com/hdu-2010/p/3706170.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!