Created
March 5, 2013 04:35
-
-
Save jrichter/5088037 to your computer and use it in GitHub Desktop.
2 different quicksort methods
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
# -*- coding: utf-8 -*- | |
def partition(array, left, right, pivotIndex) | |
pivot = array[pivotIndex] | |
array[pivotIndex], array[right] = array[right], array[pivotIndex] | |
r = right - 1 | |
storeIndex = left # copied left use as index | |
(left..r).each do |i| | |
if array[i] < pivot | |
array[i], array[storeIndex] = array[storeIndex], array[i] | |
storeIndex += 1 | |
end | |
end | |
array[storeIndex], array[right] = array[right], array[storeIndex] | |
return storeIndex | |
end | |
def quicksort(array, left, right) #http://en.wikipedia.org/wiki/Quicksort | |
if left < right #make sure list has two or more items | |
pivotIndex = left #only produces the correctly sorted array if left or right is used | |
pivotNewIndex = partition(array, left, right, pivotIndex) | |
quicksort(array, left, pivotNewIndex - 1) | |
quicksort(array, pivotNewIndex + 1, right) | |
end | |
return array | |
end | |
def quicksort2(array, left, right) #http://rosettacode.org/wiki/Sorting_algorithms/Quicksort | |
pivot_index = rand(0..(array.length - 1)) #this chooses a random pivot | |
pivot = array[pivot_index] #correctly sorts array with random pivot | |
right_original = right | |
left_original = left | |
left = left | |
right = right | |
while left <= right | |
while array[left] < pivot | |
left += 1 | |
end | |
while array[right] > pivot | |
right -= 1 | |
end | |
if left <= right | |
array[left], array[right] = array[right], array[left] | |
left += 1 | |
right -= 1 | |
end | |
quicksort2(array, left, right_original ) | |
quicksort2(array, left_original, right) | |
end | |
return array | |
end | |
array = [] | |
100.times do |i| | |
array << rand(0..100) | |
end | |
#array = [9,3,0,1,5,0,2,8,7,4,6,10,5,4,5,4,5,99,153,94,6] | |
#array = [101,55,8] | |
t = Time.now | |
p quicksort(array, 0, array.length - 1) | |
t2 = Time.now | |
p t2 - t | |
t = Time.now | |
result = quicksort2(array, 0, array.length - 1) | |
t2 = Time.now | |
p (t2 - t) | |
p result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment