希尔排序实例

实例功能:接收一个含有整数元素的数组和一个包含元素个数的整数,将数组中的元素从小到大重新排序。并输出排序前后的数组。

下面以模块划分的思想来实现此功能。

打印数组元素模块:

/* common.h */

#ifndef _COMMON_H
#define _COMMON_H

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

#endif
/* common.c */

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

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

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

希尔排序模块:

/* shell_sort.h */

#ifndef _SHELL_SORT_H
#define _SHELL_SORT_H

void shell_sort(int array[], int n);

#endif
/* shell_sort.c */

#include "shell_sort.h"

void 
shell_sort(int array[], int n)
{
    int i, j, increment;
    int tmp;
    
    for(increment = n / 2; increment > 0; increment /= 2)
    {
        for(i = increment; i < n; i++)
        {
            tmp = array[i];
            for(j = i; j >= increment; j -= increment)
            {
                if(tmp < array[j - increment])
                    array[j] = array[j - increment];
                else
                    break;
            }
            array[j] = tmp;
        }
    }
}

主函数:

/* shell_sort_test.c */

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

int 
main(void)
{
    int array[] = {34, 8, 64, 51, 32, 21};
    
    printf("Before sorted:");
    print_array(array, 6);
    shell_sort(array, 6);
    printf("After sorted :");
    print_array(array, 6);
    
    return 0;
}

Makefile文件:

/* Makefile */

target := sort_test
objs := shell_sort_test.o shell_sort.o common.o
$(target):$(objs)
    gcc -o $@ $^
%.o:%.c
    gcc -c -o $@ $<

clean:
    rm *.o sort_test

测试过程:

image

posted @ 2014-04-13 08:42  ITtecman  阅读(464)  评论(0编辑  收藏  举报