
Ola pessoa, eu estava tentando implementar o algorítimo insertion sort no R de forma recursiva, mas não estou conseguindo e também não consigo identificar onde estou errado. #Veja so. Eu tenho um vetor qualquer: vetor<-sample(100) vetor #Iterativamente ele funciona beleza, eu fiz assim: insertionsort<-function(vetor){ n<-length(vetor) for(i in 2:n) { aux=vetor[i] j=i-1 while(j>=1 && vetor[j]>aux) { vetor[j+1]<-vetor[j] j=j-1 } vetor[j+1]=aux } return(vetor) } insertionsort(vetor) #Mas quando tento usar recursão, não consigo fazer funcionar, ele não organiza insertionsortR<-function(vetor,n) { if(n>1) { insertionsortR(vetor,n-1) aux=vetor[n] i=n while(vetor[i-1]>aux && i>1) { vetor[i]<-vetor[i-1] i<-i-1 } vetor[i]<-aux } return(vetor) } insertionsortR(vetor,length(vetor)) #Usando o rcpp ele funcionou dessa forma aqui: cppFunction(" NumericVector insertionsortRC(NumericVector vetor, int n) { double aux; int i; if(n>1) { insertionsortRC(vetor,n-1); aux=vetor[n-1]; i=n-1; while(vetor[i-1]>aux && i>=0 ) { vetor[i]=vetor[i-1]; i--; } vetor[i]=aux; } return vetor; } ") insertionsortRC(vetor,length(vetor)) Alguém sabe dizer onde estou errado la no insertionsort no R. Eu imagino se estou imaginado errado o funcionamento dos vetores no R, se ele ta refazendo um novo vetor a cada chamada e no final nada da certo do jeito que estou fazendo. Recursão funciona beleza no R, por exemplo usando fatorial: fatorial<-function(n) { if(n==1) { return(1) } else { return(n*fatorial(n-1)) } } fatorial(5) Mas no caso do vetor, não entendi o funcionamento ali dos vetores, se alguém puder dar uma luz :) -- Grato Augusto C. A. Ribas Site Pessoal: http://recologia.com.br/ <http://augustoribas.heliohost.org> Github: https://github.com/Squiercg Lattes: http://lattes.cnpq.br/7355685961127056