简体   繁体   中英

JAVA: Sorting an array in descending order

I'm trying to sort an array in descending order, I know there are many examples of sorting an array online, but I just wanted to try and do it my own way (just trying to test to see if algorithm could actually work). But some reason, I'm unable to output the array with the result stored, I've tried using System.out.println(Arrays.toString(myList)); and printing them one at time, it works for one the arrays i created, but when trying to modify the array through a loop, it refused to output anything, no error, nothing as though nothing is there. Your help would be appreciated. see code below. Thanks.

import java.util.Arrays;

public class TestArray {

   public static void main(String[] args) {
      double[] myList = {1.9, 2.9, 9.2, 3.4, 4.2, 6.7, 3.5};
      double[] sortedList = new double[7] ; 


      // Print all the array elements
      for (double i: myList) {
         System.out.println(i + " ");
      }

      // Summing all elements
      double total = 0;
      for (double x: myList) {
         total += x;
      }
      System.out.println("Total is " + total);

      // Finding the largest element
      double max = myList[0];
      int m, z = 0;

      for (double k: myList) {
         if (k > max) max = k;
      }

      do{
        for (int i = m; i < myList.length; i++) {
          if (myList[i] > max){      
             max = myList[i];  
             z = i;
          }
        }

        sortedList[m] = max;
        myList[z] =0;
        m++;

      } while(m < myList.length);

      System.out.println("Max is " + max);
      //System.out.println(Arrays.toString(myList)); 
      for (double y: sortedList) {
         System.out.println(y + " ");
      }
   }
}

you can simply use inbuilt function to sort your array in descending order as

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

System.out.println("myList Array Elements in reverse order:");
    for (int i = 0; i < myList .length; i++)
       System.out.println(intArray[i]);

It will work for sure.

Your logic for sorting is not working as intended. I have made some changes to it, give it a try :

    do {
           max = 0;
           for (int i = 0; i < myList.length; i++) {
               if (myList[i] > max) {
                   max = myList[i];
                   z = i;
               }
           }

           sortedList[m] = max;
           myList[z] = 0;
           m++;

   } while (m < myList.length);

First you need to convert this line int m, z = 0; to int m = 0, z = 0; because int m, z = 0; is equivalent to int m; int z = 0; int m; int z = 0; . Hence when you try to use variable m - it is not initialized yet and that results to a compilation error. After fixing the above statement, your program will compile and run but there is also a mistake in the program logic as well and your result sorted array will be output as:

{9.2, 9.2, 9.2, 9.2, 9.2, 9.2, 9.2}

as in the following block

for (double k: myList) { if (k > max) max = k; }

you initially find the max value which is 9.2 . That's why when you later execute do .. while and check the condition here

if (myList[i] > max){ max = myList[i]; z = i; }

the statement myList[i] > max will never return true and hence your max will be always remain 9.2 and z will be always remain 0 . That's why the line sortedList[m] = max; always inserts 9.2 to each index of your sorted array.

In such cases i recommend you to use an IDE of your choice(Intellij Idea, Eclipse, etc.) which will highlight compilation errors and help you to find your bugs using the integrated debugger.

So i just found your mistakes, i think now you can manage it. In case of additional help feel free to communicate.

The following code works for me.

public class Main {

public static void main(String[] args) {
    double[] myList = {1.9, 2.9, 9.2, 3.4, 4.2, 6.7, 3.5};
    double[] sortedList = new double[7] ;


    // Print all the array elements
    for (double i: myList) {
        System.out.println(i + " ");
    }

    // Summing all elements
    double total = 0;
    for (double x: myList) {
        total += x;
    }
    System.out.println("Total is " + total);

    // Finding the largest element
    double max = myList[0];
    int m = 0;
    int z = 0;

    do{
        for (int i = 0; i < myList.length; i++) {
            if (myList[i] > max){
                max = myList[i];
                z = i;
            }
        }

        sortedList[m] = max;
        myList[z] =0;
        m++;
        max = 0;

    } while(m < myList.length);

    System.out.println("Max is " + max);
    //System.out.println(Arrays.toString(myList));
    for (double y: sortedList) {
        System.out.println(y + " ");
    }
}
}

You're code contained three errors:

1.You failed to reset 'max' in every iteration, leading to 'sortedList' containing just the value 9.2 in every entry.

  1.  for (double k: myList) { if (k > max) max = k; } 

    is unneccessary. Moreover, it doesn't even keep track where the max element is.

3.

for (int i = m; i < myList.length; i++)

should be changed to

for (int i = 0; i < myList.length; i++)

The position you're at in 'sortedList' has nothing to do with where you can find the maximum element of 'myList'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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