归并排序
2011-09-22 10:55 htc开发 阅读(139) 评论(0) 编辑 收藏 举报归并排序:二路归并排序
此算法采用自顶向下的归并排序算法,算法形式简洁,首先设排序的当前区间为a[low...high]
具体步骤:
分解:将当前区间一分为二,即求分裂点。
求解:递归地对两个子区间a[low...middle]和a[middle+1...high]进行归并排序
组合:将已排序的两个子区间a[low...middle]和a[middle+1...high]归并为一个有序的区间r[low...high]
递归总结条件:子区间长度为1(一个记录本身就是有序的)
算法的代码实现:
#include <stdio.h>
#include <stdlib.h>void merge(int a[], int temp[], int l_pos, int m_pos, int r_end)
{
int i = 0;
int left_pos = l_pos;
int l_end = m_pos;
int r_pos = m_pos + 1;
while(l_pos <= l_end && r_pos <= r_end)
{
if(a[l_pos] < a[r_pos])
{
temp[i++] = a[l_pos++];
}
else
{
temp[i++] = a[r_pos++];
}
}
while(l_pos <= l_end)
{
temp[i++] = a[l_pos++];
}
while(r_pos <= r_end)
{
temp[i++] = a[r_pos++];
}
/*copy from temp to a*/
for(i = left_pos; i <= r_end; i++)
a[i] = temp[i-left_pos];
}
void _m_sort(int a[], int temp[], int low, int high)
{
int m_pos = 0;
if(low >= high)
return ;
m_pos = (high + low) / 2;
_m_sort(a, temp, low, m_pos);
_m_sort(a, temp, m_pos+1, high);
merge(a, temp, low, m_pos, high);
}
void m_sort(int a[], int size)
{
int *temp = NULL;
temp = (int *)malloc(size*sizeof(int));
if(temp != NULL)
_m_sort(a, temp, 0, size-1);
free(temp);
}
int main(void)
{
int i = 0;
int a[] = {4,3,5,1,2};
m_sort(a, 5);
for(i = 0; i < 5; i++)
printf("%d\n", a[i]);
return 0;
}