#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>
插入法排序算法insertion sort algorithm
最新推荐文章于 2024-07-15 22:10:26 发布