Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java swap invalid

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.

console output

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?

like image 959
Maxmoe Avatar asked Jun 17 '18 08:06

Maxmoe


1 Answers

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().

like image 89
Lie Ryan Avatar answered Sep 18 '22 02:09

Lie Ryan