归并排序递归实现C语言
2010-11-20 23:11
435 查看
/* 7-13-11-20-22.33.c -- 第七章第十三题 */ #include <stdio.h> #include <stdlib.h> #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] ; }接触排序第四天,照着书上的代码写出的递归实现.思路基本理解,贴出来.
相关文章推荐
- 归并排序非递归实现C语言
- C语言实现快排、归并排序、快排改进算法的递归和非递归算法
- C语言的快速排序算法代码-递归实现
- 递归求最大最小值算法 分治策略(c语言实现)
- 数据结构排序算法之归并排序(c语言实现)
- 归并排序、二分法查找的递归实现
- <转> - 归并排序(递归实现+非递归实现+自然合并排序)
- 算法思考--------汉诺塔c语言实现-------递归
- 递归实现归并排序(基本排序算法)
- C语言-函数实现模块化设计-函数的递归调用
- C语言实现二叉树的常用的算法(递归与非递归实现遍历)
- 排序算法之(5)——归并排序(递归实现)
- 怎样使用递归实现归并排序
- (C语言)递归实现字符串反转
- 【C语言】递归实现栈的逆序及排序
- C语言实现递归删除文件夹及文件
- C语言实现二叉树的递归遍历和非递归遍历
- 【数据结构与算法】汉诺塔算法——C语言递归实现
- 常用排序算法完全版 快排优化 归并排序的非递归实现
- C语言递归和非递归实现字符串反转