Insert sort + bubble sort + select sort, insert sort bubble select
When inserting the sort work mechanism and playing cards, sorting in the hand is similar. When we started to touch the cards, our left hand was empty and placed down on the table. Next, we touched a card from the table and inserted it to the correct position in the left-hand row. In order to find the correct position of the card, compare it with none of his hands from right to left. At any time, the cards in the left hand are sorted in order. (From: Introduction to algorithms)
Example: 5, 4, 6, 2, 7, 3, 4, 1
5-> 4, 5-> 4, 5, 6-> 2, 4, 5-> 2, 5, 6, 7 --> 2, 3, 4, 5, 6, 7 --> 2, 4, 4, 5, 6, 7 --> 1, 2, 3, 4, 5, 6, 7
Insert sorting (InsertSort ):
Int InsertSort (int * a, int n) {// insert and sort the array with n length. The subscript is 0 ~ N-1 int I, j, key; for (j = 1; j <n; j ++) {key = a [j]; I = J-1; while (I> = 0 & a [I]> key) {// compare from right to left. The current element is greater than the key value, the current element is moved after a [I + 1] = a [I]; I --;} // I =-1 (all elements are moved after) | a [I] <= key, key inserted to the I + 1 position a [I + 1] = key;} return 0 ;}
Bubble Sorting: Two Adjacent Elements in reverse order are exchanged from n to subscript 1.
Here we only provide the first exchange:
5, 4, 6, 2, 4, 1 --> 5, 4, 6, 2, 7, 3,-> 5, 4, 6, 2, 7, 7, 3, 4-> 5, 6, 2, 3, 4-> 5, 6, 1, ,->,->
BubbleSort ):
/*** Call Function Method BubbleSort (A, n): Sort array A [1 .. n]; * Here we show incremental sorting */int BubbleSort (int * A, int n) {for (int I = 1; I <= n; I ++) {for (int j = n; j> = 1; j --) {// it must be from n -- 1 here. Why? If (A [j] <A [J-1]) swap (A [J-1], A [j]) ;}} return 0 ;}
Select sort: place the smallest number in the remaining number in the appropriate position. This refers to the ascending order. For each A [I], compare all elements of I + 1-> n, the swap location between A and A [I] is smaller than that of A [I.
Here we only provide the first option:
, -->, ,->, -->,->
SelectionSort ):
/*** Call Function Method SelectionSort (A, n): Sort array A [1 .. n]; * Here we show incremental sorting */int SelectionSort (int * A, int n) {for (int I = 1; I <= n; I ++) {for (int j = I + 1; j <= n; j ++) {if (A [j] <A [I]) swap (A [j], A [I]) ;}} return 0 ;}