Skip to content

Instantly share code, notes, and snippets.

@lmullen
Last active August 29, 2015 13:57
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 lmullen/9677440 to your computer and use it in GitHub Desktop.
Save lmullen/9677440 to your computer and use it in GitHub Desktop.
Quicksort algorithm in R to demonstrate recursion
quicksort <- function(x) {
if(length(x) <= 1) return(x)
pivot <- x[1]
remainder <- x[-1]
remainder_1 <- remainder[remainder < pivot]
remainder_2 <- remainder[remainder >= pivot]
remainder_1 <- quicksort(remainder_1)
remainder_2 <- quicksort(remainder_2)
return(c(remainder_1, pivot, remainder_2))
}
if (require("testthat")) {
test_that("quicksort function sorts properly", {
x <- c(1, 6, 2, 10, -9, 12, 4, -12)
y <- c(-12, -9, 1, 2, 4, 6, 10, 12)
expect_that(quicksort(x), equals(y))
expect_that(quicksort(x), equals(sort(x)))
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment