Home >Web Front-end >JS Tutorial >Detailed explanation of JS insertion sort

Detailed explanation of JS insertion sort

小云云
小云云Original
2018-03-07 10:42:242817browse

Principle: Divide the entire sorted sequence into two parts, one part has been sorted, and the other part has not been sorted. Each time, a number is removed from the unsorted sequence and inserted into the sorted sequence. In a good sequence, the unsorted number sequence is zero;

* In the sorting process, the first number of the sequence is generally regarded as the sorted sequence by default, and the remaining numbers are regarded as unsorted Good sequence

Sequence: [9,8,,7,6,5,4,3,2,1]
Divide the entire sequence into two parts:
Sorted: 9
Unsorted: 8 7 6 5 4 3 2 1
Take a number from the unsorted one and insert it into the sorted sequence
Sorted: 8 9
Unsorted: 7 6 5 4 3 2 1
Take out a number from the unsorted number and insert it into the sorted sequence
Sorted: 7 8 9
Unsorted of: 6 5 4 3 2 1
and so on until all data is sorted.

JS code implementation:

var arr=[9,8,7,6,5,4,3,2,1];for(var i=1;i<arr.length;i++){    var temp=arr[i];    var j=i-1;    while(j>=0&&arr[j]>temp){
        arr[j+1]=arr[j];
        arr[j]=temp;
        j--;
    }
    arr[j+1]=temp;
}console.log(arr);

输出结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]

Related recommendations:

JS implementation of counting sorting and radix sorting algorithm examples_javascript skills

Example analysis of basic commonly used sorting algorithms in JavaScript

Detailed explanation of Javascript array deduplication and quick sorting algorithm examples

The above is the detailed content of Detailed explanation of JS insertion sort. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn