 # Working on a homebrew quicksort function using a partition function but encountering errors

I've been working on a quicksort function which incorporates a partition function I wrote, however, I keep encountering bugs when comparing parameters of my function. It keeps telling me that my r and p comparisons are of length 0, but I thought it should be a valid comparison since I declare them as ints when I call the quicksort function. Any help would be appreciated!

``````partition <- function(input,p, r){
pivot = input[r]
while(p<r){
while(input[p]<pivot) {p<-p+1}
while(input[r]>pivot) {r<-r-1}
if(input[p]==input[r]) {p<-p+1}
else if (p<r){
tmp <- input[p]
input[p] = input[r]
input[r] = tmp
}
}
return(r)
}

quicksort<- function(input,p,r){

if(p<r){
j<- partition(input,p,r)
input <- quicksort(input,p,j-1)
input <- quicksort(input,j+1,r)

}

}

input <- c(500,700,800,100,300,200,900,400,1000,600)
print("Input:")
print(input)
quicksort(input,1,10)
print("Output:")
print(input)

``````

your partition function doesnt return anything, so j is empty.

``````quicksort<- function(input,p,r){

if(p<r){
j<- partition(input,p,r)
cat("j-1:", j - 1 , "\n")
cat("length of j:",length(j),"\n")
input <- quicksort(input,p,j-1)
input <- quicksort(input,j+1,r)
}
}``````

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

im not sure why you would return r, shouldn't you return a modifed version of input, so that input is changed in someway ?
you should either use browse(), debug() functions to step through your code, or be liberally with print() and cat() statements to let you see what you are doing.

``````partition <- function(input,p, r){
cat("entering partion with\n")
print(input)
pivot = input[r]
while(p<r){
cat("p is ",p," input[p] is ",input[p],"\n")
cat("pivot is ",pivot,"\n")
while(input[p]<pivot) {p<-p+1}
while(input[r]>pivot) {r<-r-1}
if(input[p]==input[r]) {p<-p+1}
else if (p<r){
tmp <- input[p]
input[p] = input[r]
input[r] = tmp
}
}
return(r)
}``````

I changed my partition function and added a return(r) at the end, however, it still didn't work