1

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????

Hot Licks
  • 47,103
  • 17
  • 93
  • 151
PatGreens
  • 129
  • 2
  • 10

4 Answers4

8

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];
   }
zakinster
  • 10,508
  • 1
  • 41
  • 52
1

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());
Marcin Krupa
  • 497
  • 2
  • 6
0

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;
   }
Roudy Tarabay
  • 449
  • 1
  • 4
  • 18
0

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));
Sarojini2064130
  • 221
  • 3
  • 7