/ * EXERCISE: Write a method that puts an unordered sequence of n integers in ascending order. Home (a) Using sorting by selection
(b) Using insertion ordering * /
I tried to solve the exercise, but I'm getting that result:
Original Sequence: 3 9 1 3 2 0 8 11
Sequence Selection: 0 3 1 3 2 11 8 9
Sequence Insertion: 0 1 3 2 3 8 9 11
What can I be doing wrong?
class Tres {
public static int [] ordenaSelecao (int [] array) {
int [] arraySelecao = array;
int menor = arraySelecao[0];
int posMenor = 0;
for (int i = 0; i<arraySelecao.length; i++) {
//buscando menor elemento
for (int j=i+1; j<arraySelecao.length; j++){
if (menor > arraySelecao[j]) {
menor = arraySelecao[j];
posMenor = j;
}
}
if (arraySelecao[i] > arraySelecao[posMenor]) {
int aux = arraySelecao[posMenor];
arraySelecao[posMenor] = arraySelecao[i];
arraySelecao[i] = aux;
}
}
return arraySelecao;
}
public static int [] ordenaInsercao (int [] array) {
int [] arrayInsercao = array;
for (int i=1; i<arrayInsercao.length; i++){
for (int j=i-1; j>0; j--){
if (arrayInsercao[i]<arrayInsercao[j]) {
int aux = arrayInsercao[i];
arrayInsercao[j+1] = arrayInsercao[j];
arrayInsercao[j] = aux;
}
}
}
return arrayInsercao;
}
public static void main(String[] args) {
int [] array = {3,9,1,3,2,0,8,11};
System.out.print("Sequencia Original: ");
for (int i=0; i<array.length; i++) {
System.out.print(array[i]+" ");
}
System.out.println(" ");
System.out.print("Sequencia Selecao: ");
int [] arraySelecao = ordenaSelecao(array);
for (int i=0; i<arraySelecao.length; i++) {
System.out.print(arraySelecao[i]+" ");
}
System.out.println(" ");
System.out.print("Sequencia Insercao: ");
int [] arrayInsercao = ordenaInsercao(array);
for (int i=0; i<arrayInsercao.length; i++) {
System.out.print(arrayInsercao[i]+" ");
}
}
}