Idea: each time you extract the first element from the unordered table, insert it to the proper position of the ordered table. After insertion, the ordered table continues to be ordered.
Initialization: the first element to be sorted is an ordered table. All elements except the first element constitute an unordered table.
Direct insertion sorting is composed of two nested loops. The element that identifies the outer loop and determines the sequence to be inserted. The memory loop determines the proper position for the value to be inserted, that is, the inserted ordered sequence is still an ordered sequence.
The outer loop starts with 2nd values.
In the inner loop, the value to be inserted is compared with the 1st value on the left. If the 1st value on the left is greater than the value, then, the first numeric value on the left is placed in the position next to it, that is, the position with the inserted numeric value, so save the value to be interpolated with temp), and then compare it with the first numeric value on the left, otherwise, place the value to the right of the first numeric value on the left. And so on.
# Include <stdio. h> # include <stdlib. h> void swap (int arr [], int I, int j) {int temp; temp = arr [I]; arr [I] = arr [j]; arr [j] = temp;} void InsertSort (int arr [], int n) {int I; for (I = 1; I <n; I ++) // The loop starts from 2nd array elements and shifts arr [0] As the originally sorted part {int temp = arr [I]; int j = I-1; while (j> = 0 & arr [j]> temp) {arr [j + 1] = arr [j]; j --;} arr [j + 1] = temp ;}} void print (int arr [], int n) {int I; for (I = 0; I <n; I ++) {printf ("% d", arr [I]);} printf ("\ n");} int main () {int arr [] = {9, 1, 5, 8, 3, 7, 4, 6, 2}; int n = sizeof (arr)/sizeof (arr [0]); printf ("Before sorting: \ n "); print (arr, n); InsertSort (arr, n); printf (" sorted: \ n "); print (arr, n ); system ("pause"); return 0 ;}
Complexity: O (n2)
Stable sorting
This article is from "Li Haichuan" blog, please be sure to keep this source http://lihaichuan.blog.51cto.com/498079/1282112