开发者

Java: Sorting unsorted array in descending order

开发者 https://www.devze.com 2022-12-27 02:31 出处:网络
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 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.

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?


This should get you started. You'll need to create your own Comparator and then call Collections.Sort().

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


I suggest looking at the Wikipedia article for sorting algorithms. 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.


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];
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号