我如何以升序对数组进行排序,但是要找到最大的整数?

问题描述 投票:0回答:1
public static <T extends Comparable<? super T>> void modifiedSelectionSort(T[] a, int n) {
        for( int index = 0; index < n - 1; index++) {
            int indexOfGreatest = indexofGreatest(a, index, n -1);
            T temp = a[index];
            a[index] = a[indexOfGreatest];
            a[indexOfGreatest] = temp;
        }
    }
private static <T extends Comparable<? super T>> int indexofGreatest(T[] a, int first, int last) {
    T max = a[last];
    int indexOfMax = last;
    for (int index = last; index <= first; index-- ) {
        if (a[index].compareTo(max) > 0) {
                max = a[index];
                indexOfMax = last;
            }
        }
        return indexOfMax;
    }

我希望此代码在数组中找到最大的整数,将其放在数组的后面,然后再次搜索并找到第二个最大的整数,并将其放在倒数第二个位置,依此类推,等等

java sorting selection
1个回答
0
投票
在第12行,“索引”应该是“> =”到“第一”,而不是“ <=”:

for (int index = last; index >= first; index-- ) {

© www.soinside.com 2019 - 2024. All rights reserved.