Created
December 13, 2019 13:30
-
-
Save Bablzz/98875444548100fde2a299662ca185db to your computer and use it in GitHub Desktop.
Insertion sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# O(n^2) | |
def insertion_sort arr | |
i = 0 | |
j = 0 | |
for i in 1...(arr.length) do | |
key = arr[i] | |
j = i - 1 | |
while j >= 0 and key < arr[j] do | |
arr[j + 1] = arr[j] | |
j -= 1 | |
end | |
arr[j + 1] = key | |
end | |
arr | |
end | |
arra = [1,6,0,5,12] | |
puts insertion_sort(arra) | |
# => 0 1 5 6 12 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment