C language insertion sorting
The essentials of the insert sort method are to insert each read number to the final storage array immediately, and each insert will make the array orderly.
Code:
# Include
# Include
# Define n 10 int main () {int a [n] = {-1, 3, 6, 9, 13, 22, 27,32, 49 }; /* pay attention to leave a space for the number of to be inserted */int x, j, k; x = rand () % 100; printf ("the random value of x is: % d \ n ", x); if (x> a [N-2]) {a [n-1] = x; /* if it is greater than the last number, store it in the last element */} else/* find the location to be inserted */{j = 0; while (j <= n-2 & x> a [j]) {j ++;} for (k = n-2; k> = j; k --) {/* move one digit from the last digit until the number at the position to be inserted */a [k + 1] = a [k];} a [j] = x;/* Number of inserts to be inserted */} printf ("output: \ n"); for (j = 0; j <= n-1; j ++) printf ("% d", a [j]); return 0 ;}
Running result:
Randomly generate a number and insert it into the existing array. Sort the number and output it: