(分享) 归并排序的最原始实现, 不带优化的。
各种排序是常见的面试题, 我希望能够帮助大家轻松的秒杀那些小菜鸟#include <stdio.h>
#include <stdlib.h>
#define MAX_NUM 10
void mergeSort(int a[], int left, int right);
void merge(int a[], int left, int m, int right);
int main(void)
{
int a[MAX_NUM] = {1, 3, 2, 1, 6, 1, 5, 8, 1, 0};
int i;
mergeSort(a, 0, MAX_NUM-1);
for (i = 0; i < MAX_NUM; i++)
{
printf("%d ", a[i]);
}
getchar();
return 0;
}
void merge(int a[], int left, int m, int right)
{
int aux[MAX_NUM] = {0};
int i, j, k;
for (i = left, j = m+1, k = 0; k <= right-left; k++)
{
if (i == m+1)
{
aux[k] = a[j++];
continue;
}
if (j == right+1)
{
aux[k] = a[i++];
continue;
}
if (a[i] < a[j])
{
aux[k] = a[i++];
}
else
{
aux[k] = a[j++];
}
}
for (i = left, j = 0; i <= right; i++, j++)
{
a[i] = aux[j];
}
}
void mergeSort(int a[], int left, int right)
{
int m = (right + left) / 2;
if (right <= left)
return ;
mergeSort(a, left, m);
mergeSort(a, m+1, right);
merge(a, left, m, right);
}
[ 本帖最后由 BlueGuy 于 2011-1-7 22:54 编辑 ]