用C语言实现的分治法与排序法的混合使用,使排序更为合理,高效。
/**************************************************************
* Sort.h *
* To sort numbers by mixing of INSERTION_SORT and MERGE_SORT *
* by Eric Brown *
**************************************************************/
#ifndef MIX_SORT
#define MIX_SORT
#define MIN_NUM 10
#define MAX_NUMBER 10000
void merge(int num[], int p, int q, int r);
void insertion_sort(int num[], int p, int r);
void merge_sort(int num[], int p, int r);
#endif
/************************************************
* Sort.c *
* by Eric Brown *
************************************************/
#include"Sort.h"
void merge(int num[], int p, int q, int r) {
int n1 = q - p + 1, n2 = r - q, i, j, k;
int L[n1 + 1], R[n2 + 1];
for(i = 0; i < n1; i++)
L[i] = num[p + i];
L[n1] = MAX_NUMBER;
for(i = 0; i < n2; i++)
R[i] = num[q + 1 + i];
R[n2] = MAX_NUMBER;
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 insertion_sort(int num[], int p, int r) {
int key, i, j;
for(i = p; i <= r; i++) {
key = num[i];
j = i;
while(num[j] > key) {
num[j] = num[j - 1];
j--;
}
num[j] = key;
}
}
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);
}else {
insertion_sort(num, p, r);
}
}
/*********************************************
* main.c *
* just a test *
* *
*********************************************/
#include<stdio.h>
#include<stdlib.h>
#include"Sort.h"
#define N 20
int main(void) {
int num[N], i;
printf("Please input %d numbers to sort:\n", N);
for(i = 0; i < N; i++)
scanf("%d", &num[i]);
merge_sort(num, 0, N);
for(i = 0; i < N; i++)
printf("%d ", num[i]);
printf("\n");
system("pause");
return 0;
}