Java数组降序排序?

发布于 2024-08-10 20:55:37 字数 166 浏览 8 评论 0原文

有没有简单的方法可以按降序对数组进行排序,就像在 数组类

或者我必须停止偷懒并自己做这件事:[

Is there any EASY way to sort an array in descending order like how they have a sort in ascending order in the Arrays class?

Or do I have to stop being lazy and do this myself :[

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

愛放△進行李 2024-08-17 20:55:37

您可以使用它对所有类型的对象进行排序

sort(T[] a, Comparator<? super T> c) 

Arrays.sort(a, Collections.reverseOrder());

Arrays.sort() 不能直接用于按降序对原始数组进行排序。如果您尝试通过传递 Collections.reverseOrder() 定义的反向比较器来调用 Arrays.sort() 方法,它将抛出错误

没有找到适合 sort(int[],comparator) 的方法

这对于“对象数组”(例如整数数组)可以正常工作,但不适用于原始数组(例如 int 数组)。

按降序对原始数组进行排序的唯一方法是,首先按升序对数组进行排序,然后就地反转数组。对于二维基本数组也是如此。

You could use this to sort all kind of Objects

sort(T[] a, Comparator<? super T> c) 

Arrays.sort(a, Collections.reverseOrder());

Arrays.sort() cannot be used directly to sort primitive arrays in descending order. If you try to call the Arrays.sort() method by passing reverse Comparator defined by Collections.reverseOrder() , it will throw the error

no suitable method found for sort(int[],comparator)

That will work fine with 'Array of Objects' such as Integer array but will not work with a primitive array such as int array.

The only way to sort a primitive array in descending order is, first sort the array in ascending order and then reverse the array in place. This is also true for two-dimensional primitive arrays.

成熟稳重的好男人 2024-08-17 20:55:37

对于列表

Collections.sort(list, Collections.reverseOrder());

对于数组

Arrays.sort(array, Collections.reverseOrder());

for a list

Collections.sort(list, Collections.reverseOrder());

for an array

Arrays.sort(array, Collections.reverseOrder());
独享拥抱 2024-08-17 20:55:37

您可以使用以下方法:

    Arrays.sort(data, Collections.reverseOrder());

Collections.reverseOrder() 使用逆自然顺序返回一个 Comparator。您可以使用Collections.reverseOrder(myComparator)获得您自己的比较器的反转版本。

You can use this:

    Arrays.sort(data, Collections.reverseOrder());

Collections.reverseOrder() returns a Comparator using the inverse natural order. You can get an inverted version of your own comparator using Collections.reverseOrder(myComparator).

埖埖迣鎅 2024-08-17 20:55:37

另一种方法是(对于数字!!!)

  1. 将数组乘以-1
  2. 排序
  3. 再次乘以-1

字面意思:

array = -Arrays.sort(-array)

an alternative could be (for numbers!!!)

  1. multiply the Array by -1
  2. sort
  3. multiply once again with -1

Literally spoken:

array = -Arrays.sort(-array)
锦欢 2024-08-17 20:55:37

没有显式比较器:

Collections.sort(list, Collections.reverseOrder());

有显式比较器:

Collections.sort(list, Collections.reverseOrder(new Comparator()));

without explicit comparator:

Collections.sort(list, Collections.reverseOrder());

with explicit comparator:

Collections.sort(list, Collections.reverseOrder(new Comparator()));
扎心 2024-08-17 20:55:37

使用 Arrays.sort() 和 < 无法直接对基元数组(即 int[] arr = {1, 2, 3};)进行反向排序code>Collections.reverseOrder() 因为这些方法需要引用类型 (Integer) 而不是基本类型 (int)。

但是,我们可以使用 Java 8 Stream 首先对数组进行装箱,然后按相反的顺序进行排序:

// an array of ints
int[] arr = {1, 2, 3, 4, 5, 6};

// an array of reverse sorted ints
int[] arrDesc = Arrays.stream(arr).boxed()
    .sorted(Collections.reverseOrder())
    .mapToInt(Integer::intValue)
    .toArray();

System.out.println(Arrays.toString(arrDesc)); // outputs [6, 5, 4, 3, 2, 1]

It's not directly possible to reverse sort an array of primitives (i.e., int[] arr = {1, 2, 3};) using Arrays.sort() and Collections.reverseOrder() because those methods require reference types (Integer) instead of primitive types (int).

However, we can use Java 8 Stream to first box the array to sort in reverse order:

// an array of ints
int[] arr = {1, 2, 3, 4, 5, 6};

// an array of reverse sorted ints
int[] arrDesc = Arrays.stream(arr).boxed()
    .sorted(Collections.reverseOrder())
    .mapToInt(Integer::intValue)
    .toArray();

System.out.println(Arrays.toString(arrDesc)); // outputs [6, 5, 4, 3, 2, 1]
壹場煙雨 2024-08-17 20:55:37

首先,您需要使用以下方法对数组进行排序:

Collections.sort(myArray);

然后您需要使用以下方法将顺序从升序反转为降序:

Collections.reverse(myArray);

First you need to sort your array using:

Collections.sort(myArray);

Then you need to reverse the order from ascending to descending using:

Collections.reverse(myArray);
无名指的心愿 2024-08-17 20:55:37

Java 8:

Arrays.sort(list, comparator.reversed());

更新:
reversed() 反转指定的比较器。通常,比较器按升序排列,因此这会将顺序更改为降序。

Java 8:

Arrays.sort(list, comparator.reversed());

Update:
reversed() reverses the specified comparator. Usually, comparators order ascending, so this changes the order to descending.

感性不性感 2024-08-17 20:55:37

对于包含原语元素的数组,如果有 org.apache.commons.lang(3) 可供使用,则反转数组(排序后)的简单方法是使用:

ArrayUtils.reverse(array);

For array which contains elements of primitives if there is org.apache.commons.lang(3) at disposal easy way to reverse array (after sorting it) is to use:

ArrayUtils.reverse(array);
So尛奶瓶 2024-08-17 20:55:37

当数组是 Integer 类类型时,可以使用以下方法:

Integer[] arr = {7, 10, 4, 3, 20, 15};
Arrays.sort(arr, Collections.reverseOrder());

当数组是 int 数据类型时,可以使用以下方法:

int[] arr = {7, 10, 4, 3, 20, 15};
int[] reverseArr = IntStream.rangeClosed(1, arr.length).map(i -> arr[arr.length-i]).toArray();

When an array is a type of Integer class then you can use below:

Integer[] arr = {7, 10, 4, 3, 20, 15};
Arrays.sort(arr, Collections.reverseOrder());

When an array is a type of int data type then you can use below:

int[] arr = {7, 10, 4, 3, 20, 15};
int[] reverseArr = IntStream.rangeClosed(1, arr.length).map(i -> arr[arr.length-i]).toArray();
悲喜皆因你 2024-08-17 20:55:37

我不知道您的用例是什么,但是除了这里的其他答案之外,另一个(惰性)选项是仍然按照您指示的升序排序,但然后按相反顺序进行迭代。

I don't know what your use case was, however in addition to other answers here another (lazy) option is to still sort in ascending order as you indicate but then iterate in reverse order instead.

不奢求什么 2024-08-17 20:55:37

对于上面的讨论,这里有一个简单的示例,用于按降序对原始数组进行排序。

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] nums = { 5, 4, 1, 2, 9, 7, 3, 8, 6, 0 };
        Arrays.sort(nums);

        // reverse the array, just like dumping the array!
        // swap(1st, 1st-last) <= 1st: 0, 1st-last: nums.length - 1
        // swap(2nd, 2nd-last) <= 2nd: i++,  2nd-last: j--
        // swap(3rd, 3rd-last) <= 3rd: i++,  3rd-last: j--
        //
        for (int i = 0, j = nums.length - 1, tmp; i < j; i++, j--) {
            tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }

        // dump the array (for Java 4/5/6/7/8/9)
        for (int i = 0; i < nums.length; i++) {
            System.out.println("nums[" + i + "] = " + nums[i]);
        }
    }
}

输出:

nums[0] = 9
nums[1] = 8
nums[2] = 7
nums[3] = 6
nums[4] = 5
nums[5] = 4
nums[6] = 3
nums[7] = 2
nums[8] = 1
nums[9] = 0

For discussions above, here is an easy example to sort the primitive arrays in descending order.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] nums = { 5, 4, 1, 2, 9, 7, 3, 8, 6, 0 };
        Arrays.sort(nums);

        // reverse the array, just like dumping the array!
        // swap(1st, 1st-last) <= 1st: 0, 1st-last: nums.length - 1
        // swap(2nd, 2nd-last) <= 2nd: i++,  2nd-last: j--
        // swap(3rd, 3rd-last) <= 3rd: i++,  3rd-last: j--
        //
        for (int i = 0, j = nums.length - 1, tmp; i < j; i++, j--) {
            tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }

        // dump the array (for Java 4/5/6/7/8/9)
        for (int i = 0; i < nums.length; i++) {
            System.out.println("nums[" + i + "] = " + nums[i]);
        }
    }
}

Output:

nums[0] = 9
nums[1] = 8
nums[2] = 7
nums[3] = 6
nums[4] = 5
nums[5] = 4
nums[6] = 3
nums[7] = 2
nums[8] = 1
nums[9] = 0
╄→承喏 2024-08-17 20:55:37

对于按降序排序的 2D 数组,您只需翻转参数输出的位置即可

int[][] array= {
    {1, 5},
    {13, 1},
    {12, 100},
    {12, 85} 
};
Arrays.sort(array, (a, b) -> Integer.compare(a[1], b[1])); // for ascending order
Arrays.sort(array, (b, a) -> Integer.compare(a[1], b[1])); // for descending order

降序排列

12, 100
12, 85
1, 5
13, 1

For 2D arrays to sort in descending order you can just flip the positions of the parameters

int[][] array= {
    {1, 5},
    {13, 1},
    {12, 100},
    {12, 85} 
};
Arrays.sort(array, (a, b) -> Integer.compare(a[1], b[1])); // for ascending order
Arrays.sort(array, (b, a) -> Integer.compare(a[1], b[1])); // for descending order

Output for descending

12, 100
12, 85
1, 5
13, 1
家住魔仙堡 2024-08-17 20:55:37

另一个解决方案是,如果您使用Comparable接口,您可以切换在compareTo(Object bCompared)中指定的输出值。

例如:

public int compareTo(freq arg0) 
{
    int ret=0;
    if(this.magnitude>arg0.magnitude)
        ret= 1;
    else if (this.magnitude==arg0.magnitude)
        ret= 0;
    else if (this.magnitude<arg0.magnitude)
        ret= -1;
    return ret;
}

其中 ma​​gnitude 是我的程序中数据类型为 double 的属性。这是按照我定义的类 freq 的大小以相反的顺序对其进行排序。因此,为了纠正这个问题,您可以切换 <> 返回的值。这将为您提供以下结果:

public int compareTo(freq arg0) 
{
    int ret=0;
    if(this.magnitude>arg0.magnitude)
        ret= -1;
    else if (this.magnitude==arg0.magnitude)
        ret= 0;
    else if (this.magnitude<arg0.magnitude)
        ret= 1;
    return ret;
}

要使用此compareTo,我们只需调用Arrays.sort(mFreq),它将为您提供排序后的数组freq [] mFreq

该解决方案的优点(在我看来)在于它可以用于对用户定义的类进行排序,甚至比按特定属性对它们进行排序更重要。如果 Comparable 接口的实现听起来令人畏惧,我鼓励您不要这样想,实际上并非如此。这个关于如何实现可比较的链接使事情变得更加重要对我来说更容易。希望人们能够使用这个解决方案,并且您的喜悦甚至可以与我的相媲美

Another solution is that if you're making use of the Comparable interface you can switch the output values which you had specified in your compareTo(Object bCompared).

For Example :

public int compareTo(freq arg0) 
{
    int ret=0;
    if(this.magnitude>arg0.magnitude)
        ret= 1;
    else if (this.magnitude==arg0.magnitude)
        ret= 0;
    else if (this.magnitude<arg0.magnitude)
        ret= -1;
    return ret;
}

Where magnitude is an attribute with datatype double in my program. This was sorting my defined class freq in reverse order by it's magnitude. So in order to correct that, you switch the values returned by the < and >. This gives you the following :

public int compareTo(freq arg0) 
{
    int ret=0;
    if(this.magnitude>arg0.magnitude)
        ret= -1;
    else if (this.magnitude==arg0.magnitude)
        ret= 0;
    else if (this.magnitude<arg0.magnitude)
        ret= 1;
    return ret;
}

To make use of this compareTo, we simply call Arrays.sort(mFreq) which will give you the sorted array freq [] mFreq.

The beauty (in my opinion) of this solution is that it can be used to sort user defined classes, and even more than that sort them by a specific attribute. If implementation of a Comparable interface sounds daunting to you, I'd encourage you not to think that way, it actually isn't. This link on how to implement comparable made things much easier for me. Hoping persons can make use of this solution, and that your joy will even be comparable to mine.

空城之時有危險 2024-08-17 20:55:37

在这里添加我针对几种不同场景的答案
对于数组

Arrays.sort(a, Comparator.reverseOrder());

FWIW 列出

Lists.reverse(a);

所有集合

Collections.reverse(a);

Adding my answer in here for a couple of different scenarios
For an Array

Arrays.sort(a, Comparator.reverseOrder());

FWIW Lists

Lists.reverse(a);

Any and all Collections

Collections.reverse(a);
舟遥客 2024-08-17 20:55:37

Arrays.sort(nums, Collections.reverseOrder());

但 Arrays.sort() 不适用于 int[] 等原始对象。对他们来说,它会抛出,

错误:找不到适合 sort(int[],Comparator) 的方法

Arrays.sort() 只能按升序处理原始对象。

最好转成集合然后排序

Collections.sort(Arrays.asList(nums), Collections.reverseOrder())

Arrays.sort(nums, Collections.reverseOrder());

But Arrays.sort() will not work with primitive objects like int[]. For them it will throw,

error: no suitable method found for sort(int[],Comparator)

Arrays.sort() will work with primitive objects only in increasing order.

Better to convert into a collection and then sort

Collections.sort(Arrays.asList(nums), Collections.reverseOrder())

葬花如无物 2024-08-17 20:55:37

您可以使用 stream 操作( Collections.stream()) 与 Comparator.reverseOrder()

例如,假设您有这个集合:

List<String> items = new ArrayList<>();
items.add("item01");
items.add("item02");
items.add("item03");
items.add("item04");
items.add("item04");

要按“自然”顺序打印项目,您可以使用 sorted() 方法(或将其省略并得到相同的结果):

items.stream()
     .sorted()
     .forEach(item -> System.out.println(item));

或者以降序(反向)顺序打印它们,您可以使用 sorted 方法,它采用 Comparator 并反转顺序:

items.stream()
     .sorted(Comparator.reverseOrder())
     .forEach(item -> System.out.println(item));

请注意,这要求集合已实现 Comparable(如 Integer、String 等)。

You could use stream operations (Collections.stream()) with Comparator.reverseOrder().

For example, say you have this collection:

List<String> items = new ArrayList<>();
items.add("item01");
items.add("item02");
items.add("item03");
items.add("item04");
items.add("item04");

To print the items in their "natural" order you could use the sorted() method (or leave it out and get the same result):

items.stream()
     .sorted()
     .forEach(item -> System.out.println(item));

Or to print them in descending (reverse) order, you could use the sorted method that takes a Comparator and reverse the order:

items.stream()
     .sorted(Comparator.reverseOrder())
     .forEach(item -> System.out.println(item));

Note this requires the collection to have implemented Comparable (as do Integer, String, etc.).

ゃ人海孤独症 2024-08-17 20:55:37

这里发生了很多混乱 - 人们建议非原始值的解决方案,尝试从头开始实现一些排序算法,提供涉及额外库的解决方案,展示一些 hacky 等。原始问题的答案是 50 /50。对于那些只想复制/粘贴的人:

// our initial int[] array containing primitives
int[] arrOfPrimitives = new int[]{1,2,3,4,5,6};

// we have to convert it into array of Objects, using java's boxing
Integer[] arrOfObjects = new Integer[arrOfPrimitives.length];
for (int i = 0; i < arrOfPrimitives.length; i++) 
    arrOfObjects[i] = new Integer(arrOfPrimitives[i]);

// now when we have an array of Objects we can use that nice built-in method
Arrays.sort(arrOfObjects, Collections.reverseOrder());

arrOfObjects 现在是 {6,5,4,3,2,1}。如果您有一个除整数以外的数组 - 使用相应的 object< /a> 而不是整数

There is a lot of mess going on here - people suggest solutions for non-primitive values, try to implement some sorting algos from the ground, give solutions involving additional libraries, showing off some hacky ones etc. The answer to the original question is 50/50. For those who just want to copy/paste:

// our initial int[] array containing primitives
int[] arrOfPrimitives = new int[]{1,2,3,4,5,6};

// we have to convert it into array of Objects, using java's boxing
Integer[] arrOfObjects = new Integer[arrOfPrimitives.length];
for (int i = 0; i < arrOfPrimitives.length; i++) 
    arrOfObjects[i] = new Integer(arrOfPrimitives[i]);

// now when we have an array of Objects we can use that nice built-in method
Arrays.sort(arrOfObjects, Collections.reverseOrder());

arrOfObjects is {6,5,4,3,2,1} now. If you have an array of something other than ints - use the corresponding object instead of Integer.

屋顶上的小猫咪 2024-08-17 20:55:37

对 int 数组进行降序排序的简单方法:

private static int[] descendingArray(int[] array) {
    Arrays.sort(array);
    int[] descArray = new int[array.length];
    for(int i=0; i<array.length; i++) {
        descArray[i] = array[(array.length-1)-i];
    }
    return descArray;
}

Simple method to sort an int array descending:

private static int[] descendingArray(int[] array) {
    Arrays.sort(array);
    int[] descArray = new int[array.length];
    for(int i=0; i<array.length; i++) {
        descArray[i] = array[(array.length-1)-i];
    }
    return descArray;
}
假面具 2024-08-17 20:55:37

注意:这是 N log N 时间复杂度,但更容易阅读
并了解如何执行反向排序。

此解决方案的建议归功于 Ken

    // this func sorts in n log n time complexity
    public void sort_reverse(int[] arr) {
        // 1. sort the arr in asc order
        Arrays.sort(arr);
        // 2. now sort all values in descending order
        for (int i = 0, j = arr.length - 1; i < arr.length / 2;i++) {
            int tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
            j--;
        }
    }

NOTE: this is a N log N time complexity but easier to read through
and understand how to perform sort in reverse.

credits to Ken for suggestion of this solution.

    // this func sorts in n log n time complexity
    public void sort_reverse(int[] arr) {
        // 1. sort the arr in asc order
        Arrays.sort(arr);
        // 2. now sort all values in descending order
        for (int i = 0, j = arr.length - 1; i < arr.length / 2;i++) {
            int tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
            j--;
        }
    }
温折酒 2024-08-17 20:55:37

我知道这是一个相当古老的线程,但这里是整数和 Java 8 的更新版本:

Arrays.sort(array, (o1, o2) -> o2 - o1);

请注意,对于正常升序(或 Comparator.comparingInt()),它是“o1 - o2”。

这也适用于任何其他类型的对象。说:

Arrays.sort(array, (o1, o2) -> o2.getValue() - o1.getValue());

I know that this is a quite old thread, but here is an updated version for Integers and Java 8:

Arrays.sort(array, (o1, o2) -> o2 - o1);

Note that it is "o1 - o2" for the normal ascending order (or Comparator.comparingInt()).

This also works for any other kinds of Objects. Say:

Arrays.sort(array, (o1, o2) -> o2.getValue() - o1.getValue());
爱你不解释 2024-08-17 20:55:37

这对我有用:

package doublearraysort;

import java.util.Arrays;
import java.util.Collections;

public class Gpa {


    public static void main(String[] args) {
        // initializing unsorted double array
        Double[] dArr = new Double[] {                 
            new Double(3.2),
            new Double(1.2),
            new Double(4.7),
            new Double(3.3),
            new Double(4.6),
           };
        // print all the elements available in list
        for (double number : dArr) {
            System.out.println("GPA = " + number);
        }

        // sorting the array
        Arrays.sort(dArr, Collections.reverseOrder());

        // print all the elements available in list again
        System.out.println("The sorted GPA Scores are:");
        for (double number : dArr) {
            System.out.println("GPA = " + number);
        }
    }
}

输出:

GPA = 3.2
GPA = 1.2
GPA = 4.7
GPA = 3.3
GPA = 4.6
The sorted GPA Scores are:
GPA = 4.7
GPA = 4.6
GPA = 3.3
GPA = 3.2
GPA = 1.2

This worked for me:

package doublearraysort;

import java.util.Arrays;
import java.util.Collections;

public class Gpa {


    public static void main(String[] args) {
        // initializing unsorted double array
        Double[] dArr = new Double[] {                 
            new Double(3.2),
            new Double(1.2),
            new Double(4.7),
            new Double(3.3),
            new Double(4.6),
           };
        // print all the elements available in list
        for (double number : dArr) {
            System.out.println("GPA = " + number);
        }

        // sorting the array
        Arrays.sort(dArr, Collections.reverseOrder());

        // print all the elements available in list again
        System.out.println("The sorted GPA Scores are:");
        for (double number : dArr) {
            System.out.println("GPA = " + number);
        }
    }
}

Output:

GPA = 3.2
GPA = 1.2
GPA = 4.7
GPA = 3.3
GPA = 4.6
The sorted GPA Scores are:
GPA = 4.7
GPA = 4.6
GPA = 3.3
GPA = 3.2
GPA = 1.2
葬心 2024-08-17 20:55:37
public double[] sortArrayAlgorithm(double[] array) { //sort in descending order
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array.length; j++) {
            if (array[i] >= array[j]) {
                double x = array[i];
                array[i] = array[j];
                array[j] = x;
            }
        }
    }
    return array;
}

只需使用此方法按降序对 double 类型的数组进行排序,您可以使用它对任何其他类型的数组(如 int、float 等)进行排序,只需更改“返回类型”、“参数类型”和将变量“x”类型转换为相应的类型。您还可以将 if 条件中的“>=”更改为“<=”以使顺序升序。

public double[] sortArrayAlgorithm(double[] array) { //sort in descending order
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array.length; j++) {
            if (array[i] >= array[j]) {
                double x = array[i];
                array[i] = array[j];
                array[j] = x;
            }
        }
    }
    return array;
}

just use this method to sort an array of type double in descending order, you can use it to sort arrays of any other types(like int, float, and etc) just by changing the "return type", the "argument type" and the variable "x" type to the corresponding type. you can also change ">=" to "<=" in the if condition to make the order ascending.

挖鼻大婶 2024-08-17 20:55:37

使用比较器的另一种方法

import java.util.Arrays;
import java.util.Comparator;
...

Integer[] aInt = {6,2,3,4,1,5,7,8,9,10};
Arrays.sort(aInt, Comparator.reverseOrder()  );

Another way with Comparator

import java.util.Arrays;
import java.util.Comparator;
...

Integer[] aInt = {6,2,3,4,1,5,7,8,9,10};
Arrays.sort(aInt, Comparator.reverseOrder()  );
孤檠 2024-08-17 20:55:37

有时我们练习一个例子是件好事,这里有一个完整的例子:

sortdesc.java

import java.util.Arrays;
import java.util.Collections;
class sortdesc{
public static void main(String[] args){
       // int Array
       Integer[] intArray=new Integer[]{
                 new Integer(15),
                 new Integer(9),
                 new Integer(16),
                 new Integer(2),
                 new Integer(30)};

       // Sorting int Array in descending order
       Arrays.sort(intArray,Collections.reverseOrder());

       // Displaying elements of int Array
       System.out.println("Int Array Elements in reverse order:");
       for(int i=0;i<intArray.length;i++)
          System.out.println(intArray[i]);

       // String Array
       String[] stringArray=new String[]{"FF","PP","AA","OO","DD"};

       // Sorting String Array in descending order
       Arrays.sort(stringArray,Collections.reverseOrder());

       // Displaying elements of String Array
       System.out.println("String Array Elements in reverse order:");
       for(int i=0;i<stringArray.length;i++)
          System.out.println(stringArray[i]);}}

编译它...

javac sortdec.java

调用它...

java sortdesc

< strong>输出

Int Array Elements in reverse order:
30
16
15
9
2
String Array Elements in reverse order:
PP
OO
FF
DD
AA

如果你想尝试一个字母数字数组...

//replace this line:
String[] stringArray=new String[]{"FF","PP","AA","OO","DD"};

//with this:
String[] stringArray=new String[]{"10FF","20AA","50AA"};

你会得到如下输出:

50AA
20AA
10FF

来源

It's good sometimes we practice over an example, here is a full one:

sortdesc.java

import java.util.Arrays;
import java.util.Collections;
class sortdesc{
public static void main(String[] args){
       // int Array
       Integer[] intArray=new Integer[]{
                 new Integer(15),
                 new Integer(9),
                 new Integer(16),
                 new Integer(2),
                 new Integer(30)};

       // Sorting int Array in descending order
       Arrays.sort(intArray,Collections.reverseOrder());

       // Displaying elements of int Array
       System.out.println("Int Array Elements in reverse order:");
       for(int i=0;i<intArray.length;i++)
          System.out.println(intArray[i]);

       // String Array
       String[] stringArray=new String[]{"FF","PP","AA","OO","DD"};

       // Sorting String Array in descending order
       Arrays.sort(stringArray,Collections.reverseOrder());

       // Displaying elements of String Array
       System.out.println("String Array Elements in reverse order:");
       for(int i=0;i<stringArray.length;i++)
          System.out.println(stringArray[i]);}}

compiling it...

javac sortdec.java

calling it...

java sortdesc

OUTPUT

Int Array Elements in reverse order:
30
16
15
9
2
String Array Elements in reverse order:
PP
OO
FF
DD
AA

If you want to try an alphanumeric array...

//replace this line:
String[] stringArray=new String[]{"FF","PP","AA","OO","DD"};

//with this:
String[] stringArray=new String[]{"10FF","20AA","50AA"};

you gonna get the OUTPUT as follow:

50AA
20AA
10FF

source

任谁 2024-08-17 20:55:37

有一种方法可能会有点长,但效果很好。这是一种对 int 数组进行降序排序的方法。

希望这能帮助某人,,,有一天:

public static int[] sortArray (int[] array) {
    int [] sortedArray = new int[array.length];
    for (int i = 0; i < sortedArray.length; i++) {
        sortedArray[i] = array[i];
    }
    
    boolean flag = true;
    int temp;
    while (flag) {
        flag = false;
        for (int i = 0; i < sortedArray.length - 1; i++) {
            if(sortedArray[i] < sortedArray[i+1]) {
                temp = sortedArray[i];
                sortedArray[i] = sortedArray[i+1];
                sortedArray[i+1] = temp;
                flag = true;
            }
        }
    }
    
    return sortedArray;
    
}

There is a way that might be a little bit longer, but it works fine. This is a method to sort an int array descendingly.

Hope that this will help someone ,,, some day:

public static int[] sortArray (int[] array) {
    int [] sortedArray = new int[array.length];
    for (int i = 0; i < sortedArray.length; i++) {
        sortedArray[i] = array[i];
    }
    
    boolean flag = true;
    int temp;
    while (flag) {
        flag = false;
        for (int i = 0; i < sortedArray.length - 1; i++) {
            if(sortedArray[i] < sortedArray[i+1]) {
                temp = sortedArray[i];
                sortedArray[i] = sortedArray[i+1];
                sortedArray[i+1] = temp;
                flag = true;
            }
        }
    }
    
    return sortedArray;
    
}
︶葆Ⅱㄣ 2024-08-17 20:55:37

我有以下工作解决方案

    public static int[] sortArrayDesc(int[] intArray){
    Arrays.sort(intArray);                      //sort intArray in Asc order
    int[] sortedArray = new int[intArray.length];   //this array will hold the sorted values

    int indexSortedArray = 0;
    for(int i=intArray.length-1 ; i >= 0 ; i--){    //insert to sortedArray in reverse order
        sortedArray[indexSortedArray ++] = intArray [i];
    }
    return sortedArray;
}

I had the below working solution

    public static int[] sortArrayDesc(int[] intArray){
    Arrays.sort(intArray);                      //sort intArray in Asc order
    int[] sortedArray = new int[intArray.length];   //this array will hold the sorted values

    int indexSortedArray = 0;
    for(int i=intArray.length-1 ; i >= 0 ; i--){    //insert to sortedArray in reverse order
        sortedArray[indexSortedArray ++] = intArray [i];
    }
    return sortedArray;
}
べ繥欢鉨o。 2024-08-17 20:55:37

这是我对原始类型 int 数组进行排序的方法。

int[] intArr = new int[] {9,4,1,7};
Arrays.sort(nums);
Collections.reverse(Arrays.asList(nums));

结果:

[1, 4, 7, 9]

Here is how I sorted a primitive type int array.

int[] intArr = new int[] {9,4,1,7};
Arrays.sort(nums);
Collections.reverse(Arrays.asList(nums));

Result:

[1, 4, 7, 9]
暮凉 2024-08-17 20:55:37

这适用于整数的基本类型示例。
首先是将数组按降序排序,然后循环遍历内容,但从排序数组的最后一个索引开始索引。

int[] reversedArr = new int[0];
int[] arrNum = {1, 3, 4, 2, 5};
Arrays.sort(arrNum);
int j=0;
for(int i = (arrNum.length - 1); i >= 0; i-- ) {
    reversedArr[j] = arrNum[i];
    j++;
}
System.out.println(Arrays.toString(reversedArr));

This is applicable for primitive types examples for integers.
First is to sort the array into descending order then loop through the contents but start the index into the last index of the sorted array.

int[] reversedArr = new int[0];
int[] arrNum = {1, 3, 4, 2, 5};
Arrays.sort(arrNum);
int j=0;
for(int i = (arrNum.length - 1); i >= 0; i-- ) {
    reversedArr[j] = arrNum[i];
    j++;
}
System.out.println(Arrays.toString(reversedArr));
挽袖吟 2024-08-17 20:55:37

不幸的是,在描述中排序非常复杂。命令。

最好只重载像 Arrays.sort(arr,verseOrder()) 这样的方法,

现在我看到以下选项:

int[] sortedArr = Arrays.stream(arr)
                .boxed()
                .sorted(Collections.reverseOrder())
                .mapToInt(Integer::intValue)
                .toArray();

Unfortunatley it's quite complicated to sort in desc. order.

It would be good to have just overloaded method like Arrays.sort(arr, reverseOrder())

For now I see the following option:

int[] sortedArr = Arrays.stream(arr)
                .boxed()
                .sorted(Collections.reverseOrder())
                .mapToInt(Integer::intValue)
                .toArray();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文