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
##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;}
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!