归并排序
代码:
- #define MAXSIZE 10
- void merging(int *list1,int list1_size,int *list2,int list2_size)
- {
- int i,j,k,m;
- i=j=k=0;
- int temp[MAXSIZE];
- while(i<list1_size&&j<list2_size)
- {
- if(list1[i]<list2[j])
- {
- temp[k++]=list1[i++];
- }
- else
- {
- temp[k++]=list2[j++];
- }
- }
- while(i<list1_size)
- {
- temp[k++]=list1[i++];
- }
- while(j<list2_size)
- {
- temp[k++]=list2[j++];
- }
- for(m=0;m<(list1_size+list2_size);m++) //实现归并 并把结果放到list1里
- {
- list1[m]=temp[m];
- }
- }
- void MergeSort(int k[],int n)
- {
- if(n>1)
- {
- int *list1=k;
- int list1_size=n/2;
- int *list2=k+n/2;
- int list2_size=n-list1_size;
- MergeSort(list1,list1_size);
- MergeSort(list2,list2_size);
- merging(list1,list1_size,list2,list2_size);
- }
- }
- int main()
- {
- int a[10]={5,2,6,0,3,9,1,7,4,8};
- MergeSort(a,10);
- for(int i=0;i<10;i++)
- {
- printf("%-2d ",a[i]);
- }
- printf("\n\n");
- return 0;
- }
复制代码 上面的代码是递归实现 同样也可以迭代实现 代码如下
- #define LEN 10
- void merge_sort(int *list, int length)
- {
- int i, left_min, left_max, right_min, right_max, next;
- int *tmp = (int*)malloc(sizeof(int) * length);
- if (tmp == NULL)
- {
- fputs("Error: out of memory\n", stderr);
- abort();
- }
-
- for (i = 1; i < length; i *= 2) // i为步长,1,2,4,8……
- {
- for (left_min = 0; left_min < length - i; left_min = right_max)
- {
- right_min = left_max = left_min + i;
- right_max = left_max + i;
- if (right_max > length)
- right_max = length;
- next = 0;
- while (left_min < left_max && right_min < right_max)
- tmp[next++] = list[left_min] > list[right_min] ? list[right_min++] : list[left_min++];
- while (left_min < left_max)
- list[--right_min] = list[--left_max];
- while (next > 0)
- list[--right_min] = tmp[--next];
- }
- }
- free(tmp);
-
- }
-
-
- int main(void)
- {
- int a[LEN] = { 5, 2, 4, 7, 1, 3, 8, 6 ,9 ,0 };
- merge_sort(a, LEN);
- int i;
- for (i = 0; i < LEN; i++)
- printf("%d ", a[i]);
- printf("\n");
-
- return 0;
- }
复制代码
|