Insertion Sort Algorithm
- Intuition :
Insertion Sort takes one element at a time and inserts into the correct position in the already sorted part.
- Step — by — Step explanation:
For example, [ 5 , 3 , 4 , 1 ]
- Take 3 → insert before 5 → [3, 5, 4, 1]
- Take 4 → insert between 3 and 5 → [3, 4, 5, 1]
- Take 1 → insert at beginning → [1, 3, 4, 5]
Step 1: Start from index 1
for (int i = 1; i < arr.length; i++)
We start from i = 1 because the first element 5 is considered already sorted.
[5 | 3 4 1]
↑
sorted part.
Step 2: Store current element
int key = arr[i];
For i = 1:
key = 3
We want to find the correct position for 3.
Step 3: Take previous index
int j = i - 1;
So:
j = 0
arr[j] = 5
Step 4: Compare
while (j >= 0 && arr[j] > key)
Check:
5 > 3 → true
So we move 5 one position right.
arr[j + 1] = arr[j];
Array becomes:
[5, 5, 4, 1]
Then:
j--;
Now j = -1.
Step 5: Insert the key
arr[j + 1] = key;
Since j = -1:
arr[0] = 3
Array:
[3, 5, 4, 1]
Step 6: Next element
Now:
[3, 5 | 4 1]
key = 4
Compare:
5 > 4 → shift 5
[3, 5, 5, 1]
Then insert 4:
[3, 4, 5, 1]
Step 7: Last element
[3, 4, 5 | 1]
key = 1
Shift:
5 → right
4 → right
3 → right
Then insert 1:
[1, 3, 4, 5] - Code in java :
Get Pranav Biradar’s stories in your inbox
Join Medium for free to get updates from this writer.
import java.util.Scanner;
public class InsertionSort {
static void insertionSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
insertionSort(arr);
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}- Code in C + +:
#include <iostream>
using namespace std;
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
int main() {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
insertionSort(arr, n);
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}- Time and Space Complexity:
Time: Best O(n) when the array is already sorted, because each element needs only one comparison. Average and worst case are O(n²) because elements may need to be shifted many positions.
Space: O(1) because only key and j are used as extra variables, so no additional array is required
I hope you will understand……best of luck on your journey .







