插入排序实例

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

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

打印数组元素模块:
/* 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");
}
插入排序模块:
/* insertion_sort.h */

#ifndef _INSERTION_SORT_H
#define _INSERTION_SORT_H

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

#endif
/* insertion_sort.c */

#include "insertion_sort.h"

void
insertion_sort(int array[], int n)
{
    int j, p;
    int tmp;
    
    for(p = 1; p < n; p++)
    {
        tmp = array[p];
        for(j = p; j > 0 && array[j-1] > tmp; j--)
            array[j] = array[j-1];
        array[j] = tmp;
    }
}
主函数:
/* insertion_sort_test.c */

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

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

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

clean:
    rm *.o sort_test
测试过程:

image

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值