分治法排序

#include<stdio.h>
#include<stdlib.h>
#define N 4
#define MAX 10000

void merge(int *num, int p, int q, int r);
void merge_sort(int *num, int p, int r);
int main(void) {
   int num[100];
   int i;
   printf("Please input %d numbers to sort(less than %d):\n", N, MAX);
   
   for(i = 0; i < N; i++)
       scanf("%d", &num[i]);
   
   merge_sort(num, 0, N-1);
   
   for(i = 0; i < N; i++)
       printf("%d ", num[i]);
   printf("\n");
   
   system("pause");
   return 0;
}
//将已经排好的两组数组进行排序
void merge(int *num, int p, int q, int r) {
   int n1, n2, i, j, k;
   int L[N], R[N];
   n1 = q - p + 1;
   n2 = r - q;
   for(i = 0; i < n1; i++)
       L[i] = num[p + i];
   for(i = 0; i < n2; i++)
       R[i] = num[q + i + 1];
   L[n1] = MAX;
   R[n2] = MAX;
   i = 0;
   j = 0;
   for(k = p; k <= r; k++){
       if(L[i] <= R[j]){
           num[k] = L[i];
           i++;
       } else {
           num[k] = R[j];
           j++;
       }
   }
}

void merge_sort(int *num, int p, int r) {
   int q;
   if(p < r) {
       q = (p + r) / 2;
       merge_sort(num, p, q);
       merge_sort(num, q+1, r);
       merge(num, p, q, r);
   }
}
点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注