Skip to content

Instantly share code, notes, and snippets.

@felipernb
Created August 10, 2012 08:50
Show Gist options
  • Save felipernb/3312682 to your computer and use it in GitHub Desktop.
Save felipernb/3312682 to your computer and use it in GitHub Desktop.
QuickSort in Ruby
#In-place QuickSort
def quicksort(a, l = 0, r = a.length)
return a if l >= r
p = partition(a,l,r)
quicksort(a, l, p)
quicksort(a, p+1, r)
a
end
def partition(a, l, r)
pivot = a[l] #pivot is the first element, as simple as it gets
i = l+1
for j in i..r-1 do
if a[j] < pivot
a[j], a[i] = a[i], a[j]
i += 1
end
end
a[l], a[i-1] = a[i-1], a[l]
i-1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment