How to implement compareTo in a generic method that takes a generic array as argument?

WebStormer :

I'm trying to implement a method, that, given a generic array, and two index values, slice the array, and find the largest element between the two given numbers.

<T extends Comparable<? super T>> T max(T[] array, int firstIndx, int secondIndx) {        //requires comparable
    T maxElement = array[0];      //8
    System.out.println(Arrays.toString(array));

    for (int i = firstIndx; i < secondIndx - 1; i++) {
        for (int j = firstIndx + 1; j < secondIndx; j++) {
            if (array[i].compareTo(array[j]) > 0) {
                maxElement = array[i];
                array[i] = array[j];
                array[j] = maxElement;
            }
        }
    }

    System.out.println(Arrays.toString(array));
    return maxElement;
}

But for an arrays of ints [8, 4, 6, 20, 1], is swapping correctly just the first two elements, giving me the wrong maximum elements. What's wrong with the code ?

Jordan :

There are two issues with your sort. The first is that you're using firstIndx and secondIndx, but based on how your code is structured, it's treating that second number as if it were the second index minus 1.

The second issue is that your inner loop is starting back at firstIndx every time, which breaks the bubble sort. It needs to start at i.

Try this modification to your for loops:

for (int i = firstIndx; i <= secondIndx - 1; i++) { // Notice the "<=".
    for (int j = i + 1; j <= secondIndx; j++) { // j starts at i
    // ... existing bubble sort code goes here
    }
}

Edit: I failed to mention that your approach won't find the max if the max is already in its sorted position. You should just grab the max from array[secondIndx] after you're done sorting.


As an aside, firstIndx is a pretty bad variable name. It's only one letter more to write it out in full: firstIndex.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=322923&siteId=1