简体   繁体   English

Java数组降序排列并打印其元素编号

[英]Java array sort descending and print their element number

What I am trying to do is sort an array in descending order like this 我想做的是像这样按降序对数组进行排序

Arrays.sort(array);
Collections.reverse(Arrays.asList(array));

and then print which array element was first and then second and then thrird etc.. 然后打印哪个数组元素是第一个,然后是第二个,然后是第三个,等等。

INPUT: 10 43 77 23 the descending order of them is: 77 43 23 10 I want it to print: 3 2 4 1 输入:10 43 77 23它们的降序是:77 43 23 10我要打印:3 2 4 1

If you have any questions feel free to ask me. 如果您有任何疑问,请随时问我。

Thanks you in advance! 预先谢谢您!

If I understand correct, you want to print the index of the element in the original array? 如果我理解正确,您是否要在原始数组中打印元素的索引? First you'll need to copy the array, sort the copy and then find the indices in of the sorted elements in the original array. 首先,您需要复制数组,对副本进行排序,然后在原始数组中找到已排序元素的索引。 Following code does that. 下面的代码可以做到这一点。

int[] x = Arrays.copyOf(array, array.length);
Arrays.sort(x);
Collections.reverse(Arrays.asList(x));

List listObject = Arrays.asList(array)

for(int el : x) {
    System.out.print(listObject.indexOf(el)
}

This is assuming your elements in the array are unique. 假设数组中的元素是唯一的。 If the elements in your array are of a different type, you should change the type of x and el accordingly. 如果数组中的元素属于其他类型,则应相应更改xel的类型。

You could work with a Map with the element as the key, and the index as the value. 您可以使用以元素为键,索引为值的Map You'd first have to create this map with a for loop 您首先必须使用for循环创建此映射

Map<Integer, Integer> indexLookUp = new HashMap<>();
for(int i = 0; i < array.length; i++) {
    map.put(array[i], i);
}

Then you can sort the array: 然后,您可以对数组进行排序:

Arrays.sort(array);

You don't need the reversing part, as you can just iterate the array backwards. 您不需要反转部分,因为您可以向后迭代数组。 And then print out the index for the element via the map lookup: 然后通过地图查找打印出元素的索引:

for(int i = array.length - 1; i >= 0; i--) {
    System.out.println("Element: " + array[i] + ", previous index: " + map.get(array[i]));
}

Try this: 尝试这个:

int array[] = {17, 10, 8, 13, 5, 7, 8, 30};

// Init the element list
List<Element> elements = new ArrayList<Element>();
for (int i = 0; i < array.length; i++) {
    elements.add(new Element(i, array[i]));
}

// Sort and print
Collections.sort(elements);
Collections.reverse(elements); // If you want reverse order
for (Element element : elements) {
    System.out.println(element.value + " " + element.index);
}

You can sort an array of indices instead of the array containing the actual data: 您可以对索引数组进行排序,而不是对包含实际数据的数组进行排序:

    Integer[] indices = new Integer[array.length];
    for (int i = 0; i < array.length; ++i) {
        indices[i] = i;
    }
    Arrays.sort(indices, (a, b) -> {
        return array[a] < array[b] ? 1 : array[a] > array[b] ? -1 : 0;});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM