insertion-sort.c (603B)
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 /* an implementation of insertion sort */ 5 6 void isort(int *, size_t, int); 7 8 int 9 main(int argc, char** argv) 10 { 11 int *a; 12 size_t nelem; 13 14 nelem = argc - 1; 15 a = (int *)malloc(1024); 16 17 for(int i = 0; i < nelem; i++) { 18 ++argv; 19 *(a+i) = atoi(*argv); 20 } 21 22 for (size_t i = 1; i < nelem; i++) { 23 isort(a, i, a[i]); 24 } 25 26 for (size_t i = 0; i<nelem; i++) 27 printf("%d ", a[i]); 28 printf("\n"); 29 30 free(a); 31 32 return 0; 33 } 34 35 void 36 isort(int a[], size_t i, int val) 37 { 38 int j = i - 1; 39 40 while (j >= 0 && a[j] > val) { 41 a[j+1] = a[j]; 42 j--; 43 } 44 a[j+1] = val; 45 46 return; 47 } 48