# What is Insertion Sort Algorithm?

**Digamber Rawat**Published on

A sorting algorithm where the components are shifted one by one to the right is called **insertion sort algorithm**. It helps in making a list which has been finally sorted with the motion of components that has been ranked higher, one component at one time. The advantage of insertion sort is that it is simple.

## Understand Insertion Sort

Initially, the first component in the array of an **insertion sort** is considered to be sorted. Each element in an array is checked with the element in the preceding position. This results in an output list that is increasingly sorted. The sorting array moves a component at a time and inserts the component in the correct location, with every repetition. The repetition goes on unless the sorting has been done on the whole list.

## The advantages of an insertion sort are as follows:

- It is not difficult for the purpose of implementation.
- It is applicable for small sets of data, specifically if it has been sorted in a substantial manner.
- It has low overhead. The data can be sorted in the the list as soon as the data is received.
- The amount of memory space required by the insertion sort does not fluctuate or very throughout the span of the operation. It is more efficient than bubble sort or selection sort.

an insertion sort is not that efficient on when the size of the data sets are increased.

However, an **insertion sort** is less effective on larger data sets. It is less efficient than the heap sort or quick sort.

## Solving Insertion Sort Algorithm in JavaScript

```
function insertionSort (elements) {
for (var i = 0; i < elements.length; i++) {
let val = elements[i]
for (var a = i - 1; a > -1 && elements[a] > val; a--) {
elements[a + 1] = elements[a]
}
elements[a + 1] = val
}
return itemList
}
const itemList = [8, 6, 7, 2]
console.log(insertionSort(itemList))
//Result: [2, 6, 7, 8]
```