2
I’m trying to make an algorithm for Selection Sort, just to train algorithms even, in my view my logic is right about ordering, but it is returning me an error that I do not understand.
Code:
import java.util.Scanner;
import java.util.Arrays;
public class AlgoritmosOrdenacao {
static int[] SelectionSort(int vet[]){
int aux, menor;
for (int i=0; i<vet.length-2; i++){
menor = vet[i+1];
for (int j=i+1; j<vet.length-1; j++){
if (menor > vet[j+1]){
menor = vet[j+1];
}
}
aux = vet[i];
int idx = Arrays.asList(vet).indexOf(menor);
vet[i] = menor;
vet[idx] = aux;
}
return vet;
}
public static void main(String[] args) {
// TODO code application logic here
// INPUT DO VETOR
int vet[] = new int[5];
Scanner teclado = new Scanner(System.in);
for (int i=0; i<vet.length; i++){
vet[i] = teclado.nextInt();
}
// PRINT DO VETOR ANTES DA ORDENAÇÃO
for (int z=0; z<vet.length; z++){
System.out.printf("Vet[%d] = %d\n", z, vet[z]);
}
SelectionSort(vet);
// PRINT DO VETOR DEPOIS DA ORDENAÇÃO
System.out.println("Depois da ordenação");
for (int z=0; z<vet.length; z++){
System.out.printf("Vet[%d] = %d\n", z, vet[z]);
}
}
And the whole mistake is this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at algoritmosordenacao.AlgoritmosOrdenacao.SelectionSort(AlgoritmosOrdenacao.java:48)
at algoritmosordenacao.AlgoritmosOrdenacao.main(AlgoritmosOrdenacao.java:69)
C:\Users\angel\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
FALHA NA CONSTRUÇÃO (tempo total: 5 segundos)
On the line: int idx = Arrays.asList(vet).indexOf(menor);
the Netbeans underlines vet
and makes the following suggestion:
array of confused primitive specified for vararg method.
Thank you very much for the explanation, explained me well besides having learned something new too, thank you again. = D
– Ângelo Salles