Created
April 24, 2014 20:24
-
-
Save emad-elsaid/11268323 to your computer and use it in GitHub Desktop.
simple sorting algorithms with ruby
this is a small practice for implementing simple sorting algorithms using ruby, i grabed the Pseudocode from their respective wikipedia pages and converted them to ruby, one new thing i have learned from this simple practice is swapping arrays elements in single line of code.
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
#!/usr/bin/env ruby | |
# Author : Emad Elsaid (https://github.com/blazeeboy) | |
# | |
# this script is a small practice in implementing | |
# simple sorting algorithms in ruby, i converted | |
# the sorting algorithms from wikipedia pages | |
class Array | |
# Insertion sort is a simple sorting algorithm that builds | |
# the final sorted array (or list) one item at a time. | |
# It is much less efficient on large lists than more advanced | |
# algorithms such as quicksort, heapsort, or merge sort. | |
# **wikipedia** | |
def insertion_sort! | |
(1...size).each do |i| | |
j = i | |
while j > 0 and self[j-1] > self[j] | |
self[j], self[j-1] = self[j-1], self[j] | |
j = j - 1 | |
end | |
end | |
end | |
# selection sort is a sorting algorithm, specifically an in-place | |
# comparison sort. It has O(n2) time complexity, making it | |
# inefficient on large lists, and generally performs worse | |
# than the similar insertion sort. Selection sort is noted for | |
# its simplicity, and it has performance advantages over more | |
# complicated algorithms in certain situations, | |
# particularly where auxiliary memory is limited. | |
# **wikipedia** | |
def selection_sort! | |
(0...size).each do |j| | |
# find index of minimum element in the unsorted part | |
iMin = j | |
(j+1...size).each do |i| | |
iMin = i if self[i] < self[iMin] | |
end | |
# then swap it | |
self[j], self[iMin] = self[iMin], self[j] | |
end | |
end | |
end | |
# lets try our algorithms | |
x = (1..10).to_a.shuffle | |
p 'before sort : ', x | |
x.insertion_sort! | |
p 'after sort : ', x | |
x.shuffle! | |
p 'before sort : ', x | |
x.selection_sort! | |
p 'after sort : ', x |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment