flippoc flippoc - 5 months ago 13
Ruby Question

Issues with Quicksort in Ruby

I'm having a lot of issues writing a Quicksort algorithm in Ruby. I'm coming from C++/ Java, so my code could be completely wrong:

def quicksort(*list)

if list.empty?
return list
end

$pivot = list.sample

list.delete_at(list.index($pivot))

current_element = list[0]

$smaller = Array.new
$larger = Array.new


list.each do |x|
if (list[x] <= $pivot)
$smaller << list[x]
else
$larger << list[x]
end
end

$sorted = Array.new

$sorted << self.quicksort(*$smaller)
$sorted << pivot
$sorted << self.quicksort(*$larger)

$sorted.flatten!

return *$sorted
end

myArray = [5, 4, 3, 2, 1]
sorted = Array.new(quicksort(myArray))

myArray.each do |x|
print x
end

print "\n"


This is the error that I'm getting:

My error

Can you not set an array equal to a function that returns an array, like you could in C++ or Java?

Answer

Editing your code you must have a class to define methods in IRB. In addition I fixed the bug with missing dollar before pivot.

class SortingAlgorithms
  def self.quicksort(*list)

    if list.empty?
      return list
    end

    $pivot = list.sample

    list.delete_at(list.index($pivot))

    current_element = list[0]

    $smaller = Array.new
    $larger = Array.new


    list.each do |x|
      if (list[x] <= $pivot)
        $smaller << list[x]
      else
        $larger << list[x]
      end
    end

    $sorted = Array.new

    $sorted << self.quicksort(*$smaller)
    $sorted << $pivot
    $sorted << self.quicksort(*$larger)

    $sorted.flatten!

    return *$sorted
  end
end


myArray = [5, 4, 3, 2, 1]
sorted = Array.new(SortingAlgorithms.quicksort(myArray))

myArray.each do |x|
  print x
end

print "\n"

But, beautiful ruby way provided in another thread.