TEJA GUNTUPALLI
TEJA GUNTUPALLI

Reputation: 31

Sorting shapes method error

 public static Shape [] sortShapes(Shape [] shapes) {
    int min;
    for (int i = 0; i < shapes.length; i++) {
        // Assume first element is min

        min = i;
        for (int j = i + 1; j < shapes.length; j++) {
            if (shapes[i].compareTo(shapes[j]) == -1) {
                 Shape temp = shapes[i]; 
                shapes[min] = shapes[i];
                shapes[i] = temp;

            }
        }


    }
    return shapes;
}

I am trying to write a method that will sort shapes and return the sorted array but the output doesnt give me anything, there is no output

Upvotes: 1

Views: 70

Answers (2)

Abdelhak
Abdelhak

Reputation: 8387

Try to replace these :

    int temp = shapes[i] ; **
    ...
    shapes[i] =  temp[i] ;

With:

   Shape temp = shapes[i] ;
   ...
   shapes[i] =  temp ;

Because temp is a Shape object.

Upvotes: 0

fabian
fabian

Reputation: 82461

There are multiple errors in your code:

if (shapes[min].compareTo(shapes[j]) == -1)

The contract of compareTo is a bit different. There is no guaranty that the results equals -1, if it's negative.

int temp = shapes[i]; 
shapes[min] = shapes[i];
shapes[i] =  temp[i];

This obviously can't work, since Shape != int. Also if you want to swap the Shapes at position i and min, there's something wrong with the indices:

Shape temp = shapes[i]; // save value at pos i
shapes[i] = shapes[min]; // overwrite value just saved
shapes[min] =  temp; // overwrite other value with saved value

Also return shapes; is located at the wrong position: You need to guaranty that there is a return statement or a uncaugth exception for every possible execution path. Therefore you need to put the statement at the very end of the method, not inside the outer for loop.

Upvotes: 1

Related Questions