The insertion sort algorithm in JavaScript is a simple sorting algorithm that works by building a sorted subarray one element at a time. It iterates over the array and compares each element with the sorted subarray on its left, inserting it in the correct position by shifting larger elements to the right. This process is repeated until the entire array is sorted.
Here’s a step-by-step explanation of the insertion sort algorithm in JavaScript:
- Start with an unsorted array of elements.
- Iterate over the array starting from the second element (index 1) to the end.
- For each element at the index
i
, store its value in a variable calledcurrentValue
. - Initialize a variable
j
with the value ofi - 1
. This represents the index of the element to the left ofcurrentValue
. - Compare
currentValue
with the element at the index j. If currentValue is smaller, move the element at the indexj
one position to the right (i.e.,arr[j + 1] = arr[j]
). - Decrement
j
by 1 and repeat step 5 untilj
becomes less than 0 or the element at the indexj
is smaller thancurrentValue
. - Place
currentValue
in its correct sorted position, which is at the indexj + 1
(i.e.,arr[j + 1] = currentValue
). - Repeat steps 3-7 for each remaining element in the array.
- After the iteration is complete, the array will be sorted in ascending order.
Insertion sort JavaScript example
Simple example code implementation of the insertion sort algorithm in JavaScript.
function insertionSort(arr) {
for (let i = 1; i < arr.length; i++) {
let currentValue = arr[i];
let j = i - 1;
while (j >= 0 && arr[j] > currentValue) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = currentValue;
}
return arr;
}
// Example usage:
const array = [5, 2, 4, 6, 1, 3];
const sortedArray = insertionSort(array);
console.log(sortedArray);
Output:
In this implementation, the insertionSort
function takes an array arr
as input and sorts it in ascending order using the insertion sort algorithm. It iterates through the array starting from the second element (i = 1
). It compares each element with the sorted subarray on its left and inserts it in the correct position by shifting the larger elements to the right.
The sorted subarray grows with each iteration until the entire array is sorted. Finally, the sorted array is returned.
The algorithm has a time complexity of O(n^2) in the worst case but can perform well for small or partially sorted arrays.
Comment if you have any doubts or suggestions on this JS sorting algorithm topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version