Reputation: 3
I am sorting an array in ascending and descending order. I made two methods and called them from main. The methods work fine separately but when I call them both it looks like the last one overwrites the values of the first one. I know that it should be easy but I don't understand what's going on. Could someone explain this to me?
import java.lang.reflect.Array;
public class Test {
public static void main(String[] args) {
int[] mayor, menor;
int[] array1 = new int[] {5,3,10,8,27,4,1 };
mayor= ordenMayor(array1);
menor= ordenMenor(array1);
for(int i=0; i<mayor.length ;i++) {
System.out.print(" "+mayor[i]+" ");
}
System.out.println("");
for(int i=0; i<menor.length ;i++) {
System.out.print(" "+menor[i]+" ");
}
System.out.println("");
for(int i=0; i<array1.length ;i++) {
System.out.print(" "+array1[i]+" ");
}
}
public static int[] ordenMayor(int[] arrayM) {
int[] arrayMayor=arrayM;
int mayor;
int index;
for(int i=0; i<arrayMayor.length - 1;i++) {
mayor=arrayMayor[i];
index=i;
for(int j=i; j<arrayMayor.length ;j++) {
if(arrayMayor[j]>mayor) {
mayor=arrayMayor[j];
index=j;
}
}
arrayMayor[index]=arrayMayor[i];
arrayMayor[i]=mayor;
}
return arrayMayor;
}
public static int[] ordenMenor(int[] arraym) {
int[] arrayMenor=arraym;
int menor;
int index;
for(int i=0; i<arrayMenor.length - 1;i++) {
menor=arrayMenor[i];
index=i;
for(int j=i; j<arrayMenor.length ;j++) {
if(arrayMenor[j]<menor) {
menor=arrayMenor[j];
index=j;
}
}
arrayMenor[index]=arrayMenor[i];
arrayMenor[i]=menor;
}
return arrayMenor;
}
}
the first shall be descending, the second ascending(is right) and the last one should be the array unsorted.
1 3 4 5 8 10 27
1 3 4 5 8 10 27
1 3 4 5 8 10 27
Upvotes: 0
Views: 83
Reputation: 181
This image shows a clear picture of what is happening. it just does a shallow copy or it references to the same array, array1.it is call by reference.
Upvotes: 0
Reputation: 3180
The problem is within your orderMayor
and orderMenor
methods. I will talk about orderMayor
here, since both of them have the same issues.
Specifically, the line
int[] arrayMayor = arrayM;
is reassigning arrayMayor
to be a reference to arrayM
. Notice! I said "reference". This is because this assignment doesn't actually copy the contents of the array (more technically, it only copies the address of the array Object).
What you would need is to clone the array, then operate on it, like:
int[] arrayMayor = arrayM.clone();
This creates a shallow copy of the array and assigns it to arrayMayor
, so when you operate on the array it doesn't override the old one.
Upvotes: 5