[JavaScript] --- insertion sort algorithm (reproduced teacher Alley- alley self)

First, what is called insertion sort

  There has ordered a sequence of data required in this row of good data has been inserted into the sequences of a number, but still requires the insertion of this sequence data ordered, this time is necessary to use a new sorting method - Insertion Sort law

 

Second, the core

  The basic insertion sort operation is to be inserted into a data already sorted ordered data to obtain a new, plus a number of sequenced data, sorting algorithm is suitable for small amounts of data. The insertion algorithm to sort the array into two parts: The first part contains all the elements of the array, but except for the last element (let the arrays that have a space inserted position), while the second part contains only one element of this (i.e., the element to be inserted). After completion of the first sorting section, then the last element has been inserted into the first portion sorted
 
Insertion sort of principle is well understood, the analogy can choose Sort. In two space when choosing sort, it means that each time to select the most value from the old space into the new space, and insertion sort is carried out in the same space
 
Third, the idea
  From the beginning of the second digit, each number before trying to compare one is saying and doing the exchange, and repeat this action. Until a figure does not exist or smaller than, or equal time to stop
 
                                                                           

Fourth, the code

Copy the code
var arr = [19,3,22,7,55,9,3,8]
var temp;
for(var i=1;i<arr.length;i++){
    var index = i;
    while(index-1>=0 && arr[index - 1] >arr[index]){
        [arr[index],arr[index - 1]] = [arr[index - 1],arr[index]]

        index--
    }
}


for(var i=1;i<arr.length;i++){
    var index = i;
    while(index-1>=0 && arr[index - 1] >arr[index]){
       temp = arr[index];
       arr[index] = arr[index-1];
        arr[index-1] = temp;

        index--
    }
}
Copy the code

 

Guess you like

Origin www.cnblogs.com/mp-0518/p/11440532.html