sort.h
sort.c
#include “Sort.h”
//归并排序
void _MergeSort(int* a, int begin, int end, int* tmp)
{
if (begin >= end)
return;
int mid = begin + ((end - begin) >> 1);
//子问题:对[begin,mid][mid,end]排序
_MergeSort(a, begin, mid , tmp);
_MergeSort(a, mid+1, end, tmp);
//归并[begin,mid-1][mid,end]
int begin1 = begin, end1 = mid ;
int begin2 = mid+1, end2 = end;
int index = begin;
while (begin1 <= end1&&begin2 <= end2)
{
if (a[begin1] < a[begin2])
tmp[index++] = a[begin1++];
else
tmp[index++] = a[begin2++];
}
while (begin1 <= end1)
tmp[index++] = a[begin1++];
while (begin2 <= end2)
tmp[index++] = a[begin2++];
//归并结果拷回原数组
index = begin;
while (begin <= end)
a[index++] = tmp[begin++];
}
void MergeSort(inta, int n)
{
int tmp = (int*)malloc(sizeof(int)*n);
_MergeSort(a, 0, n - 1, tmp);
free(tmp);
}
//计数排序
void CountSort(int *a, int n)
{
//计算范围
int max = a[0], min = a[0];
for (int i = 0; i <= n; ++i)
{
if (a[i] > max)
max = a[i];
if (a[i] < min)
min = a[i];
}
//统计数据个数
int range = max - min + 1;
int * count = (int*)malloc(sizeof(int)*range);
memset(count, 0, sizeof(int)*range);
for (int i = 0; i < n; ++i)
{
count[a[i] - min]++;
}
int j = 0;
for (int i = 0; i < range; ++i)
{
while (count[i]--)
{
a[j++] = i + min;
}
}
}
void TestMergeSort()
{
int a[] = { 9, 2, 1, 5, 4, 3, 6, 8, 7, 2};
MergeSort(a, sizeof(a) / sizeof(int));
printArray(a, sizeof(a) / sizeof(int));
}
void printArray(int *a, int n)
{
for (int i = 0; i < n; ++i)
{
printf("%d", a[i]);
}
printf("/n");
}
test.c