Search code examples
javaarrayssortingbubble-sort

BubbleSort for Object type of array is not working perfectly


I want to ask about bubblesort (Java)

Here's my code

Object[] bubbled = {"LMAO", 3.48 ,2.3 ,3.61 ,3.16 ,3.56 ,2.9 ,3.99 ,4.87 ,3.91};
for(int pass=1 ; pass<bubbled.length-1;pass++){
            for(int i=1;i<bubbled.length-1-pass;i++){
                if(Double.parseDouble(String.valueOf(bubbled[i]))> 
                    Double.parseDouble(String.valueOf(bubbled[i+1]))){
                    float hold= Float.parseFloat(String.valueOf(bubbled[i]));
                    bubbled[i] = bubbled[i+1];
                    bubbled[i+1] = hold;
                } 
            }
        }

The array is Object[] type. and I want it to start at bubbled[1] since bubbled[0] is non-numeric value. It does the sorting but not to my last 3 index at the end of the process.

For example:

Before : 3.48 ,2.3 ,3.61 ,3.16 ,3.56 ,2.9 ,3.99 ,4.87 ,3.91

After : 2.3 ,2.9 ,3.16,3.48 ,3.56, 3.61 ,3.99, 4.87 ,3.91

Can someone please point out what's wrong ?


Solution

  • You're not making enough passes over the array.

    for(int pass = 0; pass < bubbled.length; pass++){