Created
May 17, 2017 03:06
-
-
Save philipbroadway/ce1e286acbb6c8c2c6fc05773e99244d to your computer and use it in GitHub Desktop.
Quick Sort Module For Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Returning a sorted result:
Output
Or just sort the array itself
Output