简体   繁体   English

Java:按降序对未排序的数组进行排序

[英]Java: Sorting unsorted array in descending order

I have an unsorted array of objects. 我有未分类的对象数组。 I need to know how I can sort my array in descending order, according to the highest value inside the objects. 我需要知道如何根据对象内的最大值按降序对数组进行排序。

I need to do this using for loops, not the easy way. 我需要使用for循环来完成此操作,而不是简单的方法。

I had done this but it seems there is a problem: 我已经这样做了,但似乎有一个问题:

student[] temp=new student[s.length];

for (int i=0;i<s.length;i++)
{
    if (s[i].GetGpa() > s[i + 1].GetGpa())
    {
        temp[i] = s[i];
    }
}

How should I do it using for loops? 我应该如何使用for循环?

This should get you started. 这应该使您入门。 You'll need to create your own Comparator and then call Collections.Sort() . 您需要创建自己的Comparator ,然后调用Collections.Sort()

Collections.sort(List<T> list, Comparator<? super T> c)

I suggest looking at the Wikipedia article for sorting algorithms . 我建议查看Wikipedia文章中的排序算法 Your code fails because you compare each element only with the next one - but that's not a sorting algorithm at all, because in order to be correctly placed in the first position, an element needs to be bigger than all other elements, not just the next one. 代码失败是因为您仅将每个元素与下一个元素进行比较-但这根本不是排序算法,因为要正确放置在第一个位置,一个元素需要比所有其他元素大,而不仅仅是下一个一。

Also, Using a lowercase class name is very much against Java coding standards. 另外,使用小写的类名非常违反Java编码标准。

public class Student implements Comparable { ... }
    Arrays.sort(students);
    List<Object> list = Arrays.asList(students);
    Collections.reverse(list);
    students = list.toArray();
for (int j=0;j<s.length;j++) {
    for (int i=0;i<s.length - 1 - j;i++)
    {
        if (s[i].GetGpa() > s[i + 1].GetGpa())
        {
            student temp = s[i];
            s[i] = s[i+1];
            s[i+1] = temp;
        }
    }
}
for(int i=0;i<s.length;i++)
{
    for(int j=i+1;j<s.length;j++)
    {
        if(s[j].GetGpa()>s[i].GetGpa())
        {
            student[] temp=new student[5];
            temp[j]=s[j];
            s[j]=s[i];
            s[i]=temp[j];
        }
    }
}

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

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