Вопрос

I have looked at comparators and algorithms but I cannot make much sense of them. The comparator thing from java.util.Collections. So I chose to use this:

//return an array in descending order, using set algorithm
    public int[] descendSort()
    {
       int[] tempArray = new int[temps.length];

       for (int i = temps.length-1; i <= 0; --i)  
       {
            tempArray[i] = temps[i];
       }

    return tempArray;
    }         

my created array in my client is this:

int[] temps1 = new int[]{45, 76, 12, 102, 107, 65, 43, 67, 81, 14};

My output ended up like this:.

The temperatures in descending order is:  0 0 0 0 0 0 0 0 0 0

WHY????

Это было полезно?

Решение

The condition i <= 0 will never be met.

Also, tempArray[i] = temps[i]; will just copy the array as is.

Either do:

   for (int i = temps.length-1; i >= 0; --i)  
   {
        tempArray[temps.length-1-i] = temps[i];
   }

or simply

   for (int i = 0; i < temps.length; ++i)  
   {
        tempArray[temps.length-1-i] = temps[i];
   }

Другие советы

One-liner (doesn't work on primitives):

Integer[] temps1 = new Integer[] { 45, 76, 12, 102, 107, 65, 43, 67, 81, 14 };

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

How are you sorting anything,you are just copying from one array to another. Here is a sorting code using a selection sort. public int [] descsort(){ for(int i=0,imax)//if there is a bigger element,keep track of it int index=j;

       int temp=temps[max];
       temps[max]=temps[index];

       temps[index]=temp;

     }
        return temps;
   }

Sorting Integer array in descending order can be done in this way:

Comparator comparator = new Comparator() {

        @Override
        public int compare(Integer o1, Integer o2) {
            return o2.compareTo(o1);
        }
    };
    Integer[] array = new Integer[] { 9,1, 0, 7, 0, 0, 0, 5, 0 };
    Arrays.sort(array, comparator);
    System.out.println(Arrays.toString(array));
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top