First, what is called the insertion sorting method
There is an ordered sequence of data that requires a number to be inserted into the sorted data sequence, but the data sequence is still ordered after insertion, and a new sorting method is used-the insertion sort method
Second, the core
the basic operation of inserting a sort is to insert a data into the ordered data that is already sorted, so as to get a new sequential data with a number plus one, the algorithm is suitable for the ordering of a small amount of data. The insertion algorithm divides the array to be sorted into two parts: the first part contains all the elements of the array, except for the last element (where an array has more space to insert), and the second part contains only that element (that is, the element to be inserted). After the first part is sorted, the last element is inserted into the first part of the sequence. the principle of insertion sorting is very well understood and can be analogous to the selection of sorts. Selecting sort is done in two spaces, which means that each time you choose the most value from the old space to place the new space, and the insertion sort is done in the same spacethird, the ideastarting with the second digit, each number tries to compare and swap with the previous one and repeat the action. Stop until the previous number is absent or smaller or equal
Four, the code
vararr = [19,3,22,7,55,9,3,8]vartemp; for(vari=1;i<arr.length;i++){ varindex =i; while(index-1>=0 && arr[index-1] >Arr[index]) {[Arr[index],arr[index-1]] = [arr[index-1],arr[index]] Index-- }} for(vari=1;i<arr.length;i++){ varindex =i; while(index-1>=0 && arr[index-1] >Arr[index]) {Temp=Arr[index]; Arr[index]= Arr[index-1]; Arr[index-1] =temp; Index-- }}
"JavaScript algorithm"---insert sort