首页 / 操作系统 / Linux / Linux下归并排序(Merge Sort)下归并排序算法的C语言实现
在Linux下实现了一个归并排序的算法,分成多个文件,这里记录三点:归并排序的算法、makefile的使用、gdb调试心得一、归并排序算法算法的递推关系:一个大的数列需要排序,把它从中间分成两部分,每一部分归并排序,然后把排好序的这两个部分再合并起来(合并的时候要按顺序合并)。算法的Base Case:如果分成的这部分只有一个数,那么这个部分就不用再排序(看做已经排好序的)。实现这个算法用了三个函数,每个函数在一个文件中,分别为:merge.c sort.c 和 main.c,其中merge.c实现的是合并的方法,sort.c实现的是排序的方法,main.c是一个测试实例。还有三个头文件,分别指出了函数原型。merge.c:/*This is a merge program. * Given an integer ARRAY and three numbers which indicate the begain *and the end of two subarrays, merge the two subarrays to a bigger *one. The two subarrays are alrealy sorted from small to big. * For example, given an array a[10] and three numbers 0, 3 and 5. The *first array is from a[0] to a[2], the seconde array is from a[3] to *a[4]. The number 3 and 5 are the upper side. This program merge the *two arrays together. * */ #include <stdio.h> #include <stdlib.h>
#include "main.h"
void merge(int *a, int idxa, int idxb, int idxc) { int i = idxa, j = idxb, k = 0; int total = idxc-idxa; //int temp[total] = {0}; int *temp = (int *)malloc(sizeof(int) * total); if(temp == NULL) { fprintf(stderr, "malloc error in merge function
"); return; } while(i < idxb && j < idxc) { if(a[i] < a[j]) temp[k++] = a[i++]; else temp[k++] = a[j++]; }