Skip to content

Instantly share code, notes, and snippets.

@rebordao
Last active August 29, 2015 14:11
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 rebordao/16d94597b7d6061c7da6 to your computer and use it in GitHub Desktop.
Save rebordao/16d94597b7d6061c7da6 to your computer and use it in GitHub Desktop.
A quicksort implementation to sort an array without using conventional functions.
"
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