android 根据另一个数组中的值对数组排序

7gs2gvoe  于 2023-03-27  发布在  Android
关注(0)|答案(2)|浏览(105)

我有两个数组第一个数组(points)是arrayOf(22,8,17,13,20)和第二个是一个空数组.我如何设置第二个数组的评级,根据第一个数组中的点.例如,最大值是22,所以第二个数组中的第一个元素将具有值1.第二,第一个数组中的最大值是20,所以第二个数组的最后一个元素的值是2,最后第二个数组的下一个元素是(1,5,3,4,2),实现这个的最佳方法是什么?

5uzkadbs

5uzkadbs1#

试试这样的方法:

fun rankArray(unranked: Array<Int>): Array<Int> {
    val sorted = unranked.sortedArrayDescending() //create a temp array sortest from greatest to least
    val final = ArrayList<Int>() //create a arraylist because it's expandable
    for(element in unranked) final.add(sorted.indexOf(element) + 1) //add to the list the ranking from greatest to least in the same order as the data originally was
    return final.toTypedArray() //return result as array not arraylist
}
nmpmafwu

nmpmafwu2#

创建一个类

class ValueAndIndex implements Comparable<ValueAndIndex> {
    final int value;
    final int index;

    ValueAndIndex(int value, int index) {
        this.value = value;
        this.index = index;
    }

    @Override public int compareTo(ValueAndIndex other) {
        // compare on value;
        if (this.value > other.value) {
            return -1;
        } else if (this.value < other.value) {
            return 1;
        } else {
            return 0;
        }
    }
}

然后粘贴此代码

int[] intArray1 = {22, 8, 17, 13, 20};
        List<ValueAndIndex> secondaryList = new ArrayList<>(intArray1.length);
        for (int i = 0; i < intArray1.length; ++i) {
            secondaryList.add(new ValueAndIndex(intArray1[i], i+1));
        }
        Collections.sort(secondaryList);
        int [] indexesInSortedOrder = new int[intArray1.length];
        for (int i = 0; i < secondaryList.size(); ++i) {
            indexesInSortedOrder[i] = secondaryList.get(i).index;
        }
        Log.d("Array", Arrays.toString(indexesInSortedOrder));

输出:[1,5,3,4,2]

相关问题