Skip to content

Instantly share code, notes, and snippets.

@kotp
Forked from AudreyJean/arrays2.rb
Created February 21, 2012 22:52
Show Gist options
  • Save kotp/1879604 to your computer and use it in GitHub Desktop.
Save kotp/1879604 to your computer and use it in GitHub Desktop.
sort without using the built in SORT method
# a little program to accept a list of words, sort them without using the sort method, and output them in alphabetical order
i, j = 0, 0 # initialization of index variables
words, words2 = [], []
a_word = 'a' # dummy initialization to get into the until loop below
puts "Type a word and press <Enter> (Enter a blank line to quit):"
# Loop to accept an unspecified number of words-- creates original array
until a_word.empty?
a_word = gets.chomp
unless a_word.empty?
words.push a_word
i += 1
end # end if
end # end until
while words.length > 0
i = words.length - 1
# I will sort by looking for the lowest value word in the original array and pushing it on to the new array
a_word = words[0] # initialize with the first element in the array
a_index = 0
for j in 1..i
b_word = words[j] # assign second element to a var
if a_word.upcase > b_word.upcase # compare the two words
a_word = words[j]
a_index = j # variable so I can reference the words pushed onto the new array
end # end if
end # end for
words2.push a_word # push smallest word onto new array
words.delete_at(a_index) # delete the lowest element in the original array
i -= words.length
end # end while
puts words2
@kotp
Copy link
Author

kotp commented Feb 22, 2012

Testing code blocks

def hello(name)
  "Hello World!"
end

I just did the backticks three times, then added ruby as the language and then wrote the code and ended with the same 3 backticks. However, you can always look at the GitHub Flavored Markdown link available just above the comment window for some guidance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment