归并排序算法递归c语言,归并排序递归实现C语言

/*7-13-11-20-22.33.c -- 第七章第十三题*/

#include

#include

#define SIZE 8

int main (void) ;

void print_array (const int * const array, const int size) ;

void merge_sort (int * const array, const int size) ;

void merge_sort_entity (int * const array, int * const temp, const int left_position, const int right_position) ;

void merge (int * const array, int * const temp, int left_position, int right_position, int right_end) ;

int main (void)

{

int array[SIZE] = {3, 1, 4, 1, 5, 9, 2, 6} ;

int size = SIZE ;

print_array (array, size) ;

merge_sort (array, size) ;

print_array (array, size) ;

return 0 ;

}

void print_array (const int * const array, const int size)

{

int i ;

for (i = 0; i < size; i++)

printf ("%d ", array[i]) ;

putchar ('/n') ;

}

void merge_sort (int * const array, const int size)

{

int * temp ;

temp = (int *) malloc (sizeof (int) * size) ;

if (temp)

{

merge_sort_entity (array, temp, 0, size - 1) ;

free (temp) ;

}

else

puts ("Out of space.") ;

}

void merge_sort_entity (int * const array, int * const temp, const int left_position, const int right_position)

{

int center ;

if (left_position < right_position)

{

center = (left_position + right_position) / 2 ;

merge_sort_entity (array, temp, left_position, center) ;

merge_sort_entity (array, temp, center + 1, right_position) ;

merge (array, temp, left_position, center + 1, right_position) ;

}

}

/*left_position = start of left half, right_position = start of right half*/

void merge (int * const array, int * const temp, int left_position, int right_position, int right_end)

{

int i, left_end, count, temp_position ;

left_end = right_position - 1 ;

temp_position = left_position ;

count = right_end - left_position + 1 ;

/*main loop*/

while (left_position <= left_end && right_position <= right_end)

{

if (array[left_position] <= array[right_position])

temp[temp_position++] = array[left_position++] ;

else

temp[temp_position++] = array[right_position++] ;

}

while (left_position <= left_end)

temp[temp_position++] = array[left_position++] ;

while (right_position <= right_end)

temp[temp_position++] = array[right_position++] ;

for (i = 0; i < count; i++, right_end--)

array[right_end] = temp[right_end] ;

}   接触排序第四天,照着书上的代码写出的递归实现.思路基本理解,贴出来.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值