Skip to content

Instantly share code, notes, and snippets.

@philipbroadway
Created May 17, 2017 03:06
Show Gist options
  • Save philipbroadway/ce1e286acbb6c8c2c6fc05773e99244d to your computer and use it in GitHub Desktop.
Save philipbroadway/ce1e286acbb6c8c2c6fc05773e99244d to your computer and use it in GitHub Desktop.
Quick Sort Module For Array
module QuickSort
module InstanceMethods
def swap(arr, a, b)
arr[a], arr[b] = arr[b], arr[a]
end
def partition(arr, left, right)
pivot = ((left + right) / 2).floor
while left <= right do
while arr[left] < arr[pivot] do
left = left + 1
end
while arr[right] > arr[pivot] do
right = right - 1
end
if left <= right
swap(arr, left, right)
left = left + 1
right = right - 1
end
end
left
end
def quicksort!(arr = [], left = 0, right = self.count - 1)
if arr == []
arr = self
end
pivot = partition(arr, left, right)
if left < pivot - 1
quicksort!(arr, left, pivot - 1)
end
if right > pivot
quicksort!(arr, pivot, right)
end
arr
end
def quicksort(arr = [], left = 0, right = self.count - 1)
if arr == []
arr = self.clone
end
pivot = partition(arr, left, right)
if left < pivot - 1
quicksort(arr, left, pivot - 1)
end
if right > pivot
quicksort(arr, pivot, right)
end
arr
end
end
def self.included(receiver)
receiver.send :include, InstanceMethods
end
end
class Array
include QuickSort
end
@philipbroadway
Copy link
Author

philipbroadway commented May 17, 2017

Returning a sorted result:

example = [213,3,6,7,8,2,5,7,8.3,7]
result = example.quicksort
puts result
puts example

Output

[2, 3, 5, 6, 7, 7, 7, 8, 8.3, 213]
[213,3,6,7,8,2,5,7,8.3,7]

Or just sort the array itself

example.quicksort!
puts example

Output

[2, 3, 5, 6, 7, 7, 7, 8, 8.3, 213]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment