public class InsertionSortExample
{
public static void main(String[] args)
{
int[] arr = {50, 80, 30, 60, 10, 40, 20, 70};
// Insertion Sort
for (int i = 1; i < arr.length; i++)
{
int temp = arr[i];
int j = i - 1;
// Move elements of arr[0..i-1] that are greater than temp
// to one position ahead of their current position
while (j >= 0 && arr[j] > temp)
{
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
// Print sorted array
for (int no : arr)
{
System.out.print(no + " ");
}
}
}
Sorted Array: 10 20 30 40 50 60 70 80
Case | Description | No. of Comparisons | Time Complexity |
---|---|---|---|
Worst Case | Array is in reverse order; maximum comparisons and shifts required. | n(n-1)/2 |
O(n²) |
Average Case | Elements are in random order; comparisons and shifts required for insertion. | n²/4 |
Θ(n²) |
Best Case | Array is already sorted; only one comparison per element. | n-1 |
Ω(n) |
O(1)
→ only a few variables used; no extra memory needed.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
We’re here to make our tutorials better based on your thoughts and suggestions.