常见排序之归并排序
Posted muzixiaofeng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了常见排序之归并排序相关的知识,希望对你有一定的参考价值。
#include <stdio.h>
#include <stdlib.h>
#define ELEMENT_CNT 10
void merge(int *array,int low,int mid,int high)
{
int i,k;
int left_low = low;
int left_high = mid;
int right_low = mid+1;
int right_high = high;
int *temp = (int *)malloc((high-low+1)*sizeof(int));
if(!temp)
{
return;
}
for(k = 0; left_low <= left_high && right_low <= right_high; k++)
{
if(array[left_low] < array[right_low])
{
temp[k] = array[left_low++];
}
else
{
temp[k] = array[right_low++];
}
}
if(left_low <= left_high)
{
for(i = left_low; i <= left_high; i++)
{
temp[k++] = array[i];
}
}
if(right_low <= right_high)
{
for(i = right_low; i <= right_high; i++)
{
temp[k++] = array[i];
}
}
for(i = 0; i < (high-low+1); i++)
{
array[low+i] = temp[i];
}
free(temp);
return;
}
void merge_sort(int *array,int low,int high)
{
int mid = 0;
if(low < high)
{
mid = (low+high)/2;
merge_sort(array,low,mid);
merge_sort(array,mid+1,high);
merge(array,low,mid,high);
}
}
void trease_array(int *array)
{
int i;
for(i = 0; i < ELEMENT_CNT; i++)
{
printf("%d ",array[i]);
}
}
int main(void)
{
int array_sort[ELEMENT_CNT] = {6,4,7,3,8,2,9,1,5,0};
trease_array(array_sort);
merge_sort(array_sort,0,ELEMENT_CNT-1); //此处长度为ELEMENT_CNT-1
trease_array(array_sort);
return 0;
}
以上是关于常见排序之归并排序的主要内容,如果未能解决你的问题,请参考以下文章