Back to list
Insertion Sort
Builds the final sorted array one item at a time. Efficient for small data sets.
Initial ArrayItems: 8
96
0
65
1
67
2
93
3
75
4
26
5
93
6
52
7
Sorted Region
Key (Floating)
Shifting
Speed
Comp
0
Shifts
0
Array Controls
Time Complexity
Best
O(n)Avg
O(n²)Worst
O(n²)Very efficient for small or nearly sorted datasets. Worst case is reverse sorted.
Space Complexity
Auxiliary Space
O(1)Insertion sort sorts the array in-place.
Algorithm Details
Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part.
How it works
- Iterate from arr[1] to arr[n] over the array.
- Compare the current element (key) to its predecessor.
- If the key element is smaller than its predecessor, compare it to the elements before. Move the greater elements one position up to make space for the swapped element.
Complexity
- Time Complexity: O(n²)
- Space Complexity: O(1)