# [R] Variation of bubble sort (based on divisors)

Piotr Koller pittbox33 at gmail.com
Fri Mar 31 20:16:02 CEST 2017

```Hi, I'd like to create a function that will sort values of a vector on a
given basis:

-zeros

-ones

-numbers divisible by 2

-numbers divisible by 3 (but not by 2)

-numbers divisible by 5 (but not by 2 and 3)

etc.

I also want to omit zeros in those turns. So when I have a given vector of
c(0:10), I want to receive 0 1 2 4 6 8 10 3 9 5 7 I think it'd be the best
to use some variation of bubble sort, so it'd look like that

sort <- function(x) {
for (j in (length(x)-1):1) {
for (i in j:(length(x)-1)) {
if (x[i+1]%%divisor==0 && x[i]%%divisor!=0) {
temp <- x[i]
x[i] <- x[i+1]
x[i+1] <- temp
}
}
}
return(x)}

This function works out well on a given divisor and incresing sequences.

sort <- function(x) {
for (j in (length(x)-1):1) {
for (i in j:(length(x)-1)) {
if (x[i+1]%%5==0 && x[i]%%5!=0) {
temp <- x[i]
x[i] <- x[i+1]
x[i+1] <- temp
}
}
}
return(x)
}

x <- c(1:10)
print(x)
print(bubblesort(x))

This function does its job. It moves values divisible by 5 on the
beginning. The question is how to increase divisor every "round" ?

Thanks for any kind of help

[[alternative HTML version deleted]]

```