Home > Web Front-end > JS Tutorial > body text

Detailed explanation of JS insertion sort

小云云
Release: 2018-03-07 10:42:24
Original
2798 people have browsed it

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]
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!