开发者

Is it possible to bubblesorting an array of objects?

开发者 https://www.devze.com 2023-02-16 09:18 出处:网络
I have an array of objects populated by a .txt file Object[] punteggiTutti = scores.toArray(); Even if it\'s pos开发者_StackOverflow社区sible to use the .sort function:

I have an array of objects populated by a .txt file

Object[] punteggiTutti = scores.toArray();

Even if it's pos开发者_StackOverflow社区sible to use the .sort function:

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

I would know how to apply a working bubblesort algorithm; I tried the following not working code:

for(int i=0; i<j; i++) 
    {
    if(punteggiTutti[i]<punteggiTutti[i+1])  // error "<" operator cannot be used in objects 
      {
      temp=punteggiTutti[i]; 
      punteggiTutti[i]=punteggiTutti[i+1];
      punteggiTutti[i+1]=temp;
      }
    }


You can't compare two Objects with < operator.

Use something which implements Comparable interface. Then such elements can be compared using function a.compareTo(b);

http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Comparable.html

Also have a look at: http://leepoint.net/notes-java/data/expressions/22compareobjects.html

Try to read about equality in Java. This should help you with future errors when using Java.


Create an Comparator for your object, to compare on object against the other. The built in mergeSort algorithm is much faster than bubblesort.

http://www.iti.fh-flensburg.de/lang/algorithmen/sortieren/sortcontest/sortcontest.htm http://www.sorting-algorithms.com/

0

精彩评论

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

关注公众号