I'm working on a method aimed at sorting an array in ascending order. The array consists of earthquake marker objects, and what I need to do is sorting the array by the "magnitude" property of the objects. I tried selection sort but it seems that the elements aren't swapped properly.
Here is my code:
private void sortAndPrint(int numToPrint){
Object[] quakeArray= quakeMarkers.toArray();
int indexMax;
for(int i=0; i<quakeArray.length-1; i++) {
indexMax = i;
float max = ((EarthquakeMarker)(quakeArray[i])).getMagnitude();
for( int j =i+1; j<quakeArray.length;j++){
if(((EarthquakeMarker)(quakeArray[j])).getMagnitude()>max)
indexMax = j;
}
//swap it
Object temp = quakeArray[i];
quakeArray[i] = quakeArray[indexMax];
quakeArray[indexMax] = temp;
}
//sort finished
for(int i =0; i< numToPrint; i++) {
System.out.println(((EarthquakeMarker)quakeArray[i]).getProperty("title").toString());
}
}
It turned out that the quakes aren't sorted by their magnitude.
From my perspective, there might be something wrong with the swap because Java is passing by value. If so, how can I fix it? Or does the problem lay somewhere else?
Your selection sort logic is incorrect. You never set max when you detected a new higher-valued entry. You probably want to either update max whenever you update indexMax, or to remove max and just use indexMax instead.
For a more practical approach, in most cases you probably should use built-in functionalities when they're available such as Array.sort().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With