插入排序实例

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

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

打印数组元素模块:

/* 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("
");
}

插入排序模块:

/* 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

原文地址:https://www.cnblogs.com/nufangrensheng/p/3657887.html