Quick_sort.rb

This content was produced by an LLM and could include errors.

This script defines and uses a recursive quick_sort function in Ruby, which efficiently sorts an array by selecting a pivot and recursively sorting the remaining elements.

# frozen_string_literal: true
#=> nil

def quick_sort(data)
  return data if data.size <= 1
  pivot = data.shift
  left = []
  right = []
  
  data.each do |element|
    pivot > element ? (left << element) : (right << element)
  end
  quick_sort(left) + [pivot] + quick_sort(right)
end
#=> :quick_sort

data = [5, 3, 4, 0, 2, 9, 6, 8, 7, 1]
#=> [5, 3, 4, 0, 2, 9, 6, 8, 7, 1]
p quick_sort(data)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Ruby 4.0.3