Insertion sort in JavaScript Implementation Algorithm and Pseudocode
Here, we are sharing the code f Insertion sort in JavaScript Implementation Algorithm and Pseudocode. It is a simple sorting algorithm used to arranging the array list in a sequence by using ascending or descending order. Insertion sort is not the best algorithm than selection sort, bubble sort and merge sort in term of performance in practical scenarios.Algorithm of Insertion sort
Insertion.sort (A) { For j=2 to length A.length Key=A[i] // insert A[j] into sorted sequence i= j-1 while (i>0 and A[i]>Key) A [i+1] = A[i] i = i-1 A [i=1] = Key } i j key=48 | 4 | 5 | 3 | 6 | 7 |
8 | 8 | 5 | 3 | 6 | 7 |
4 | 8 | 5 | 3 | 6 | 7 |
4 | 8 | 8 | 3 | 6 | 7 |
4 | 5 | 8 | 3 | 6 | 7 |
4 | 5 | 8 | 8 | 6 | 7 |
4 | 5 | 5 | 8 | 6 | 7 |
4 | 4 | 5 | 8 | 6 | 7 |
3 | 4 | 5 | 8 | 6 | 7 |
3 | 4 | 5 | 8 | 8 | 7 |
3 | 4 | 5 | 6 | 8 | 8 |
3 | 4 | 5 | 6 | 7 | 8 |
Implementation of Insertion sort in Javascript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<button onclick="sortbyalphabetically()">Sort Alpha</button> <button onclick="sortbynumerically()">Sort Num</button> <p id="sortresult"></p> <script> var points = [60, 110, 4, 7, 55, 30]; document.getElementById("sortresult").innerHTML = points; function sortbyalphabetically() { points.sort(); document.getElementById("sortresult").innerHTML = points; } function sortbynumerically() { points.sort(function(a, b) {return a - b} ); document.getElementById("sortresult").innerHTML = points; } </script> |
