Created
June 5, 2013 14:38
-
-
Save dmgarland/5714332 to your computer and use it in GitHub Desktop.
An insertion sort solution
This file contains hidden or 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
| class Array | |
| def insertion_sort(list = self) | |
| sorted = [self.delete_at(0)] | |
| self.each_with_index do |i, p| | |
| if i < sorted.last | |
| sorted.each_with_index do |j, k| | |
| if sorted[k] >= i | |
| already_sorted = sorted.slice(0, k - 1) | |
| to_shift = sorted.slice(k + 1, sorted.size) | |
| sorted = already_sorted + [i] + to_shift | |
| break | |
| end | |
| end | |
| end | |
| end | |
| sorted | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment