A quicksort algorithm to demonstrate recursion. Adapted from Norman Matloff, The Art of R Programming (San Francisco: No Starch Press, 2011), 176.
Last active
August 29, 2015 13:57
-
-
Save lmullen/9677440 to your computer and use it in GitHub Desktop.
Quicksort algorithm in R to demonstrate recursion
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
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