1
/*EXERCISE: Write a method that puts in ascending order a disordered sequence of n integer.
(a) Using sorting by selection
(b) Using sorting by insertion*/
I tried to solve the exercise, but I’m getting this result:
Original sequence: 3 9 1 3 2 0 8 11
Selection sequence: 0 3 1 3 2 11 8 9
Insertion sequence: 0 1 3 2 3 8 9 11
What could 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]+" ");
}
}
}
I didn’t know that if I wrote . clone() in an array it cloned automatically. Thank you, I understood all <3
– Juliana