package
0.0.0-20240717210230-cb72c3092e0b
Repository: https://github.com/ashinzekene/algorithms.git
Documentation: pkg.go.dev
# README
Insertion sort
Time Complexity
O(N2)
Instructions
Starting from the second element, the element checks from the beginning of the array checking if any element is greater than it and them swapping it if it is.
Example: [2, 5, 3, 1, 4, 8, 7]
- Compare
5
and2
. Is 2 is smaller, so continue.[2, 5, 3, 1, 4, 8, 7]
- Compare
3
and5
,5
isn't smaller, so swap3
with5
, stop there since2
is less than3
[2, 3, 5, 1, 4, 8, 7]
- Compare
1
and5
,5
isn't smaller, so swap1
with5
, swap, 3 and 2 too[1, 2, 3, 5, 4, 8, 7]
- Compare
4
and5
,5
isn't smaller, so swap4
with5
, stop there since3
is less than4
[1, 2, 3, 4, 5, 8, 7]
- Compare
8
and5
,5
. 8 is not smaller so leave[1, 2, 3, 4, 5, 8, 7]
- Compare
7
and8
,5
. 7 is smaller so swap with 8, stop there since5
is less than7
[1, 2, 3, 4, 5, 8, 7]