歸併排序例項

weixin_34402090發表於2014-04-15

通用函式:

/* common.h */

#ifndef _COMMON_H
#define _COMMON_H

void swap(int *ap, int *bp);
void print_array(const int array[], int n);

#endif
/* common.c */

#include "common.h"
#include <stdio.h>

void 
swap(int *ap, int *bp)
{
    int tmp;
    
    tmp = *ap;
    *ap = *bp;
    *bp = tmp;
}

void 
print_array(const int array[], int n)
{
    int i;

    for(i = 0; i < n; i++)
        printf("%d ", array[i]);
    printf("\n");
}

歸併排序函式:

/* merge_sort.h */

#ifndef _MERGE_SORT_H
#define _MERGE_SORT_H

void merge(int array[], int tmparray[], int lpos, int rpos, int rightend);
void msort(int array[], int tmparray[], int left, int right);
void merge_sort(int array[], int n);

#endif
/* merge_sort.c */

#include "merge_sort.h"
#include <stdio.h>
#include <stdlib.h>

/* lpos = start of left half, rpos = start of right half */
void 
merge(int array[], int tmparray[], int lpos, int rpos, int rightend)
{
    int i, leftend, num_elements, tmpos;

    leftend = rpos - 1;
    tmpos = lpos;
    num_elements = rightend - lpos + 1;
    
    /* main loop */
    while(lpos <= leftend && rpos <= rightend)
    {
        if(array[lpos] <= array[rpos])
            tmparray[tmpos++] = array[lpos++];
        else
            tmparray[tmpos++] = array[rpos++];
    }
    
    while(lpos <= leftend)    /* copy rest of first half */
        tmparray[tmpos++] = array[lpos++];
    while(rpos <= rightend)    /* copy rest of second half */
        tmparray[tmpos++] = array[rpos++];
    
    /* copy tmparray back */
    for(i = 0; i < num_elements; i++, rightend--)
        array[rightend] = tmparray[rightend];
}

void 
msort(int array[], int tmparray[], int left, int right)
{
    int center;
    
    if(left < right)
    {
        center = (left + right) / 2;
        msort(array, tmparray, left, center);
        msort(array, tmparray, center + 1, right);
        merge(array, tmparray, left, center + 1, right); 
    }
}
void 
merge_sort(int array[], int n)
{
    int * tmparray;
    
    tmparray = malloc(n * sizeof(int));
    if(tmparray != NULL)
    {
        msort(array, tmparray, 0, n - 1);
        free(tmparray);
    }
    else
    {
        printf("No space for tmp array!!!\n");
        exit(1);
    }
}

測試函式:

/* merge_sort_test.c */

#include "max_heap_sort.h"
#include <stdio.h>

int 
main(void)
{
    int array[] = {31, 24, 45, 67, 54, 87, 98, 12, 15, 89};
    heap_sort(array, 10);
    print_array(array);
}

Makefile:

/* Makefile */

target := test
objs := merge_sort_test.o merge_sort.o common.o
$(target):$(objs)
    gcc -o $@ $^
%.o:%.c
    gcc -c -o $@ $<

clean:
    rm *.o test

測試結果:

image

相關文章