loading...

Discussion on: Quick Sort in Ruby

Collapse
kdraypole profile image
Kobe Raypole

Congrats on finishing Flatiron! Your code looks great, but I agree with Matthieu. Part of writing good Ruby code is having the code explain itself by reading variable/method names. We write code for people, not computers:) I had an interesting thought. Since the only thing that we are sorting is an array, we could add this to the class to simplify things even farther down. It's generally not a good idea to modify ruby classes, but for the sake of learning I thought it would be interesting to try

class Array
  def quick_sort(from_index = 0, to_index = length - 1)
     if from_index < to_index
       pivot_index = partition_and_get_pivot_index(from_index, to_index)
       quick_sort(from_index, pivot_index - 1)
       quick_sort(pivot_index + 1, to_index)
     end
     return self
   end

   def partition_and_get_pivot_index(from_index, to_index)
     pivot_value = self[to_index]
     pointer_a_index = pointer_b_index = from_index

     while pointer_a_index < to_index
       if self[pointer_a_index] <= pivot_value
         swap_values(pointer_a_index, pointer_b_index)
         pointer_b_index += 1
       end
       pointer_a_index += 1
     end
     swap_values(pointer_b_index, to_index)
     return pointer_b_index
   end

   def swap_values(index_a, index_b)
     self[index_a], self[index_b] = self[index_b], self[index_a]
   end
end

now if we have an array arr = [4, 3, 5, 1, 2]
we can run

arr.quick_sort 
# >> [1, 2, 3, 4, 5]
Collapse
mwong068 profile image
Megan Author

Thanks so much Kobe! 😊

That's an awesome thought, and I appreciate you sharing that implementation. It's definitely another great way to approach the problem!