Last active
August 29, 2015 14:11
-
-
Save rebordao/16d94597b7d6061c7da6 to your computer and use it in GitHub Desktop.
A quicksort implementation to sort an array without using conventional functions.
This file contains 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
" | |
A quicksort implementation to sort an array without using conventional functions. | |
It has two phases and it's a divide and conquer approach: | |
- partition phase | |
- sort phase | |
There is a nice video that demonstrates this concept using | |
Hungarian dance at https://www.youtube.com/watch?v=ywWBy6J5gz8 | |
" | |
sort_vect <- function(vect) { | |
" | |
Sorts a vector recursively using the quicksort algorithm. | |
" | |
if (length(vect)) { | |
# Gets a random element because using the first one is less effective | |
pivot <- sample(vect, 1) | |
# Picks the values smaller and bigger than the pivot, the partition phase | |
lower <- vect[vect < pivot] | |
upper <- vect[vect > pivot] | |
# This deals with cases where the pivot is repeated | |
pivots <- vect[vect == pivot] | |
return(c(sort_vect(lower), pivots, sort_vect(upper))) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment