A Beginner's Guide to Insertion Sort Algorithm with Javascript Example.
Insertion sort is a simple sorting algorithm that builds the final sorted list, one item at a time. It works by repeatedly taking an unsorted item, and inserting it in the correct position within the sorted portion of the list.
The algorithm starts by assuming that the first element of the array is already sorted. It then takes the second element and compares it to the first. If the second element is smaller, it is inserted in the correct position. If not, the algorithm moves on to the next element.
This process continues for the entire array. The outer loop keeps track of the current position in the unsorted portion of the array, and the inner loop compares each element in the sorted portion to the current element and moves it to the right until the correct position is found.
It is important to note that insertion sort has a time complexity of O(n^2) and it is not efficient for large datasets. It is simple to understand and easy to implement but not recommended for production use. In best case scenario, when the array is already sorted, its time complexity is O(n)
In summary, the insertion sort algorithm builds the final sorted list, one item at a time. It works by repeatedly taking an unsorted item, and inserting it in the correct position within the sorted portion of the list. It can be useful for small datasets or as a learning exercise, but for larger datasets, more efficient sorting algorithms should be used.
Here is an example of insertion sort implemented in JavaScript:
function insertionSort(arr) {
for (let i = 1; i < arr.length; i++) {
let current = arr[i];
let j = i - 1;
while (j >= 0 && arr[j] > current) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = current;
}
return arr;
}
console.log(insertionSort([5, 3, 6, 2, 10]));
This implementation starts with the second element of the array. It takes the current element, and compares it to the element before it, if the element before it is greater than the current element, it gets shifted to the right and the current element is inserted in the correct position. The inner "while" loop compares the current element with the elements in the sorted portion and moves them to the right until the correct position is found.
It is to be noted that the time complexity of this algorithm is O(n^2) and it is not recommended for large datasets. It is a simple algorithm to learn and understand, but not the most efficient one. In best case scenario, when the array is already sorted, its time complexity is O(n)
In summary, the insertion sort algorithm builds the final sorted list, one item at a time. It works by repeatedly taking an unsorted item, and inserting it in the correct position within the sorted portion of the list. It can be useful for small datasets or as a learning exercise, but for larger datasets, more efficient sorting algorithms should be used.
Comments
Post a Comment