DEV Community

Discussion on: Quick Sort in Ruby

Collapse
 
mdegoys profile image
Matthieu • Edited

This is great, thanks for sharing :)

Also, if I may, I have three comments/questions about your code:

  • I think in ruby snake_case is preferred for method names (see github.com/rubocop-hq/ruby-style-g...)
  • I'm not sure to understand why the conversion to_i is needed in this line if array[i].to_i <= pivot.to_i as it seems to me the values are already integers ?
  • It was a little hard for me to understand the code as I didn't know about the algorithm. Maybe using variables names that reveal the intention would help make it easier to read ? For my own usage I just changed in your code the variables names, following your explanations, to help me understand :
def quick_sort(array, from_index = 0, to_index = array.length - 1)
  if from_index < to_index
    pivot_index = partition_and_get_pivot_index(array, from_index, to_index)
    quick_sort(array, from_index, pivot_index - 1)
    quick_sort(array, pivot_index + 1, to_index)
  end
  return array
end

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

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

def swap_values(array, index_a, index_b)
  array[index_a], array[index_b] = array[index_b], array[index_a]
end
Collapse
 
mwong068 profile image
Megan • Edited

Hey Matthieu! Thanks for the comments.

I appreciate you pointing out the snake_case, I've had a bit of trouble keeping those straight as I've been moving around in languages haha. I've corrected that in the code.

As for the conversion, I simply kept that line there in case anyone ran into problems. When I was testing the code in repl.it, the conversion to integer was necessary so I didn't want anyone to run into the same error as me.

And I love what you did with the renaming of the variables and creating the swapping function. I think that is really helpful and I'll definitely keep it in mind for my next article. Thanks again for your thoughtful discussion!