# Insertion sort in JavaScript Implementation  Algorithm and Pseudocode

## 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=4

 8 4 5 3 6 7

1         2          3         4        5       6       indexes

In this case, we consider the j loop first because if you select the first number, then you have to compare this with the second number. So, you can start from 2nd number. Key=A[i] it means that Key=4, i starts from 1st number.

Key =4

i=0

 8 8 5 3 6 7

Here i= j-1, In this case, I go to 0 and goes to out of the loop.

i         j                                                 Key =5

 4 8 5 3 6 7

By performing A [i=1] = Key, 8 is replaced with 4, and increment in j.

i

 4 8 8 3 6 7

In this step, i goes to left and it takes place at number 8(array index 2) and now you can compare again. i is not greater than key so, you can perform i = i-1 and goes to 0 and then perform A [i=1] = Key and  8 is located as key.

i            j                                        Key =3

 4 5 8 3 6 7

Now compare again

i                                                                Key =3

 4 5 8 8 6 7

In this step 8 is overriding and I goes to at number 5

i

 4 5 5 8 6 7

At this stage, i goes to number 4 according to i = i-1

i=0

 4 4 5 8 6 7

Now you can compare with key =3 and i goes to 0 according to i = i-1

i            j                     Key =6

 3 4 5 8 6 7

In this case, you can again compare i and j, i is greater than 0

i

 3 4 5 8 8 7

In this step, i is not greater than key =6 and it goes out of the loop.

i         j                  Key =7

 3 4 5 6 8 8

According to A [i=1] = Key and compare again

Key =7

 3 4 5 6 7 8

Output