#include <stdio.h> //展示数组(声明) void show(int num[], int length); int main(void) { //初始化 int num[5] = {1, 8, 7, 5, 2}, i = 0, j = 0; printf("Your array is:\n"); show(num, 5); //遍历数组 for (i = 1; i < 5; i++) { int k = num[i]; j = i - 1; //依次往后移,直至找到第一个满足小于K的值 while (j >= 0 && num[j] > k) { num[j + 1] = num[j]; j--; } //将K查到该值前面 num[j + 1] = k; } printf("After sort,your array is:\n"); show(num, 5); return 0; } //展示数组(定义) void show(int num[], int length) { for (int i = 0; i < length; i++) { printf("%3d", num[i]); } printf("\n"); }
插入排序
2023-10-18 18:26:58