# Insertion Sort

**Insertion Sort** algorithm takes input, an unsorted array or any other sequential data-structure and sorts the same in-place, one element at a time. The idea is similar to how a player sorts the playing cards in hand.

It is not the most optimum algorithm and performs poorly for large data sets. The average case complexity is $O(n^2)$. Consider the following example:

For the given input array: $\{10,8,11,3,5\}$, following steps are performed:

- Element at second position ($1^{st}$ index) is compared with the previous element and is swapped if required. Thus $\{10,8,11,3,5\}$ becomes $\{8,10,11,3,5\}$.
- After that, $11$ is compared with $10$ but as these two are in order, no swapping is performed.
- Next, $3$ is compared with $11$, $10$ and $8$ and is found to be less than all these. Hence these three elements will be shifted one place to the right and $3$ will be positioned at index $0$.
- In the next step, $5$ is compared with $11$, $10$ and $8$ and these are shifted to one place to the right making space for $5$ at index $1$.
- With the completion of above step, we have our array sorted in increasing order.

It can be easily observed that the worst case scenario happens when all of the elements are already sorted in reverse order.

#### Pseudo Code

- Initialize :
**length**: length of input array.

- For every element from index 1 to length:
- set
**currentElement**= element at index**i**. - For
**all**the elements present at left of**currentElement**, which are greater than**currentElement**:- Shift the elements to one place towards right.

- Finally, set the
**currentElement**on the newly created spot after shifting elements to the right.

- set

#### Java Implementation

```
public int[] sort(int[] input) {
int length = input.length;
for (int startIndex = 1; startIndex < length; startIndex++) {
int pivot = input[startIndex];
int prevIndex = startIndex - 1;
while (prevIndex >= 0 && input[prevIndex] > pivot) {
//shift to right
input[prevIndex + 1] = input[prevIndex];
prevIndex--;
}
input[prevIndex + 1] = pivot;
}
return input;
}
```

A working java example with test case can be found here.