0

I'm trying to sort an array, but for the exercise I can't use the sort method.

Since I also have to return the empty array, as well as one with only one item in it, I kinda cheated around those. Technically I only have to sort up to three items, but this seems like a situation to use while maybe?

Here's what I've got so far.

def my_sort(input)
  if input[0] == nil
    print "[]"
  elsif input[1] == nil
    print "[" + input[0].to_s + "]"
  end
end

I'm wondering if I should be breaking this into strings or if there's some kind of .each do || that can be done.

2
  • Could we see an example of what you're trying to sort? Commented Jun 15, 2012 at 20:02
  • It's a coding problem, not anything 'real' but I'd rather do it "right" rather than just answer the conditions provided. That said, the only array to be sorted has three elements [3,1,2] Commented Jun 15, 2012 at 20:15

2 Answers 2

3

Sounds like you're asking for a sorting algorithm. There are lots, but something like insertion sort is probably one of the easiest ones to implement, or a bubble sort, perhaps, if there aren't too many numbers to sort.

Maybe this SO post will help.

Sign up to request clarification or add additional context in comments.

Comments

0

If you are only sorting three items, I would recommend a Bubble sort. All you need to do is go through the array, one element at a time. Swap the value of the current element with the next element if they are out of order. It is a really terrible algorithm for big lists; but it is a nice, easy introduction to sorting algorithms.

2 Comments

Yup. That was what I needed! Thanks! [going to investigate this "Cocktail Sort" over a cocktail actually... ]
It's worth noting that bubble sort is, on average, the worst performing (i.e. slowest) sort. Most standard library sort implementation use either merge sort or quick sort, or some hybrid or variant of the two.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.