插入排序:
1 #include <stdio.h> 2 #define LEN 5 3 4 int a[LEN] = {10, 5, 2, 4, 7}; 5 6 void print(void) 7 { 8 for (int i = 0; i < LEN; i++) 9 printf(" %d", a[i]); 10 printf("\n"); 11 } 12 13 void insertion_sort(void) //该算法要求背诵 14 { 15 int j, key; 16 for (int i = 1; i < LEN; i++) 17 { 18 print(); 19 20 key = a[i]; 21 for (j = i - 1; j >= 0 && a[j] > key; j--) 22 a[j + 1] = a[j]; 23 24 a[j + 1] = key; 25 } 26 print(); 27 } 28 29 int main(void) 30 { 31 insertion_sort(); 32 return 0; 33 }
选择排序:
#include <stdio.h> #define LEN 5 int a[LEN] = {10, 5, 2, 4, 7}; void print(void) { for (int i = 0; i < LEN; i++) printf(" %d", a[i]); printf("\n"); } void selection_sort(void) //该算法要求背诵 { int min, low; for (int i = 0; i < LEN - 1; i++) { print(); min = a[i]; low = i; for (int j = i + 1; j < LEN; j++) { if (a[j] < min) { min = a[j]; low = j; } } a[low] = a[i]; a[i] = min; } print(); } int main(void) { selection_sort(); return 0; }
原文:https://www.cnblogs.com/echo1937/p/10134311.html