How to useInsertion Sort in Javascript
Insertion sort is a simple sorting algorithm that works similarly to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part.
The algorithm iterates through the array, and for each element, it places it in the correct position within the already sorted portion of the array.
Example: This example shows the implementation of the insertion sort algorithm.
function insertionSort(arr) {
let len = arr.length;
for (let i = 1; i < len; i++) {
let key = arr[i];
let j = i - 1;
// Move elements of arr[0..i-1], that are greater than key,
// to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
return arr;
}
const array = [5, 3, 9, 1, 7];
const sortedArray = insertionSort(array);
console.log("Sorted Array (Ascending):", sortedArray);
Output
Sorted Array (Ascending): [ 1, 3, 5, 7, 9 ]
JavaScript Program to Sort the Elements of an Array in Ascending Order
Sorting an array in ascending order means arranging the elements from smallest element to largest element. we will learn to sort an array in ascending order in JavaScript.
These are the following methods:
Table of Content
- Using the sort method
- Using a for loop
- Using Insertion Sort
Contact Us