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

Detailed explanation of insertion sort in JavaScript

韦小宝
Release: 2018-03-14 14:13:45
Original
1439 people have browsed it

This article talks about insertion sorting in JavaScript. If you don’t know about insertion sorting in JavaScript, let’s take a look at this article. This article uses JavaScript to simply implement it. Insertion sort, let’s stop talking nonsense and get to the point

Insertion sort in JavaScript

Although there is no code implementation for insertion sort Bubble sort and selection sort are so simple and crude, but its principle should be the easiest to understand, because anyone who has played poker should be able to understand it instantly. Of course, if you say that you never sort the cards according to their size when playing poker, then you probably won’t have any interest in the insertion sort algorithm in this life. . .

Insertion sort, like bubble sort, also has an optimization algorithm called split-half insertion. For this kind of algorithm, I, being lazy, will use a classic saying from the textbook: interested students can study it on their own after class. . .

Insertion sort animation demonstration

Detailed explanation of insertion sort in JavaScript

##JavaScript code implementation:

function insertionSort(arr) {  
    var len = arr.length;  
    var preIndex, current;  
    for (var i = 1; i < len; i++) {  
        preIndex = i - 1;  
        current = arr[i];  
        while(preIndex >= 0 && arr[preIndex] > current) {  
            arr[preIndex+1] = arr[preIndex];  
            preIndex--;  
        }  
        arr[preIndex+1] = current;  
    }  
    return arr;}
Copy after login

The above is all the content of this article, if you haven’t If you know it well, you can easily master it if you can realize more of both sides by yourself!



Related recommendations:

Detailed explanation of JS insertion sort

PHP sorting algorithm series Insertion sort example sharing

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

Related labels:
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