The working mechanism of the insertion sort and the arrangement of the rows in the hand when playing cards are similar. In the beginning, our left hand is empty, the ranking is down on the table, then, one hand from the table to touch a card, and put it in the right hand row of the correct position. In order to find the correct position of this card, he and his hands do not have a oh from the right to the left to compare, no matter what time, the left hand in the cards are in good order. (derived from: Introduction to Algorithms)
Example: 5,4,6,2,7,3,4,1
5->4,5->4,5,6->2,4,5,6->2,4,5,6,7-->2,3,4,5,6,7-->2,3,4,4,5,6,7-->1,2,3,4,4,5,6,7
Insert Sort (insertsort):
int insertsort (int *a,int N) {//to an array of length n, Insert Sort, subscript 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) {//a right-to-left comparison, the current element is greater than the key value, and the current element moves back a[i+1 ]=a[i]; i--; } //i==-1 (all elements are moved back) | | A[i]<=key,key Insert to i+1 position a[i+1 ]=key; } return 0 ;}
Bubble sort: from N to subscript 1 two adjacent elements per exchange reverse order
Only the first exchange is given here:
5,4,6,2,7,3,4,1-->5,4,6,2,7,3,1,4->5,4,6,2,7,1,3,4->5,4,6,2,1,7,3,4->5,4,6,1,2,7,3,4-> 5,4,1,6,2,7,3,4->5,1,4,6,2,7,3,4->1,5,4,6,2,7,3,4
Bubble sort (bubblesort):
/** * How to call Functions Bubblesort (A,n): Sort Arrays a[ 1..N]; * All given are ascending sort */ int bubblesort (int *a,< Span class= "Hljs-keyword" >int N) {for (int i=1 ; i<=n;i++) {for (int j=n;j>=1 ; j--) {// This must be from n--1, think about why? if (A[j]<a[j-1 ]) swap (A[j-1 ],a[j]); }} return 0 ;}
Select sort: Each time the smallest number in the remaining number is placed in the appropriate position, this refers to the ascending sort, to each a[i], to compare all elements of i+1->n, which will be less than a[i] exchange position with A[i].
Only the first choice is given here:
5,4,6,2,7,3,4,1-->4,5,6,2,7,3,4,1-->4,5,6,2,7,3,4,1-->2,5,6,4,7,3,4,1-->2,5,6,4,7,3,4,1-> 2,5,6,4,7,3,4,1-->2,5,6,4,7,3,4,1-->2,5,6,4,7,3,4,1->1,5,6,4,7,3,4,2
Select Sort (selectionsort):
/** *调用函数的方式SelectionSort(A,n):排序数组A[1..n]; *这里给出的都是递增排序 */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]); } } return0;}
Insert Sort + bubble sort + Select sort