Quicksort

Ruby code posted by Me
created at 05 Dec 08:21

Edit | Back
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def quicksort(array)
  return array if array.length <= 1

  pivot_index = (array.length / 2).to_i
  pivot_value = array[pivot_index]
  array.delete_at(pivot_index)

  lesser = Array.new
  greater = Array.new

  array.each do |x|
    if x <= pivot_value
      lesser << x
    else
      greater << x
    end
  end

  return quicksort(lesser) + [pivot_value] + quicksort(greater)
end

names=[145, 125, 487, 2, 65, 10, 45, 78, 21]
sorted_names = quicksort(names)
puts sorted_names
500 Bytes in 3 ms with coderay