插入法排序算法insertion sort algorithm

#include"stdio.h"

typedef unsigned char uint8_t;

void print_array(uint8_t* array, uint8_t n)
{
    for(uint8_t i = 0; i < n; i++)
    {
       printf("%d, ", array[i]);
    }

    printf("\n");
}

void insert_sort(uint8_t* array, uint8_t n)
{
    uint8_t j; 
    for(uint8_t i = 1; i < n; i++ )
    {
        uint8_t temp;

        temp = array[i];  // get one element out of the array
        
        j = i - 1;          // the element before array[i] by one index

        while((j >= 0) && (temp < array[j])) // if the temp < the elemnt before which
        {
           array[j + 1] = array[j];  // move the element to right by one index
           j--; // move the index to left by one index
        }

        array[++j] = temp;  //inser temp into the space which made of moving the element

        printf("%d cycle:", i);//
        print_array(array, n);//
    }
}

void main(void)
{
    uint8_t array[] = {122,89,12,3,4,5,2,78,12,45};
    uint8_t len =  sizeof(array)/sizeof(array[0]);

    printf("the initial array is:");
    print_array(array, len);
    insert_sort(array,len);

    printf("the sorted array is:");
    print_array(array, len);
}

// PS E:\006-Programing\007-c> gcc -o output main.c
// PS E:\006-Programing\007-c> ./main
// the initial array is:122, 89, 12, 3, 4, 5, 2, 78, 12, 45, 
// 1 cycle:89, 122, 12, 3, 4, 5, 2, 78, 12, 45, 
// 2 cycle:12, 89, 122, 3, 4, 5, 2, 78, 12, 45, 
// 3 cycle:3, 12, 89, 122, 4, 5, 2, 78, 12, 45, 
// 4 cycle:3, 4, 12, 89, 122, 5, 2, 78, 12, 45, 
// 5 cycle:3, 4, 5, 12, 89, 122, 2, 78, 12, 45, 
// 6 cycle:2, 3, 4, 5, 12, 89, 122, 78, 12, 45, 
// 7 cycle:2, 3, 4, 5, 12, 78, 89, 122, 12, 45, 
// 8 cycle:2, 3, 4, 5, 12, 12, 78, 89, 122, 45, 
// 9 cycle:2, 3, 4, 5, 12, 12, 45, 78, 89, 122,
// the sorted array is:2, 3, 4, 5, 12, 12, 45, 78, 89, 122,
// PS E:\006-Programing\007-c>
  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值