Skip to content

Instantly share code, notes, and snippets.

@andrewsouthard1
Created May 20, 2017 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewsouthard1/eddff6980e17080ca4c6a026b463f340 to your computer and use it in GitHub Desktop.
Save andrewsouthard1/eddff6980e17080ca4c6a026b463f340 to your computer and use it in GitHub Desktop.
def quicksort(arr, first, last)
if first < last
p_index = partition(arr, first, last)
quicksort(arr, first, p_index - 1)
quicksort(arr, p_index + 1, last)
end
arr
end
def partition(arr, first, last)
# first select one element from the list, can be any element.
# rearrange the list so all elements less than pivot are left of it, elements greater than pivot are right of it.
pivot = arr[last]
p_index = first
i = first
while i < last
if arr[i] <= pivot
temp = arr[i]
arr[i] = arr[p_index]
arr[p_index] = temp
p_index += 1
end
i += 1
end
temp = arr[p_index]
arr[p_index] = pivot
arr[last] = temp
return p_index
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment