简体   繁体   English

JAVA:按降序对数组进行排序

[英]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)); 但是由于某些原因,我无法输出存储结果的数组,我尝试使用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; 首先,您需要将此行转换为int m, z = 0; to int m = 0, z = 0; int m = 0, z = 0; because int m, z = 0; 因为int m, z = 0; is equivalent to int m; int z = 0; 等价于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. 因此,当您尝试使用变量m尚未初始化时,将导致编译错误。 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 . 您最初发现的最大值是9.2。 That's why when you later execute do .. while and check the condition here 这就是为什么当您稍后执行do .. while并在此处检查条件时的原因

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 . 语句myList[i] > max将永远不会返回true ,因此您的max将始终保持9.2且z将始终保持0 That's why the line sortedList[m] = max; 这就是为什么那行sortedList[m] = max; always inserts 9.2 to each index of your sorted array. 总是在已排序数组的每个索引中插入9.2。

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. 在这种情况下,我建议您使用自己选择的IDE(Intellij Idea,Eclipse等),该IDE将突出显示编译错误并帮助您使用集成的调试器查找错误。

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.您没有在每次迭代中重置“ max”,从而导致“ sortedList”在每个条目中仅包含值9.2。

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

    is unneccessary. 是不必要的。 Moreover, it doesn't even keep track where the max element is. 而且,它甚至不跟踪max元素的位置。

3. 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'. 您在“ sortedList”中所处的位置与可以找到“ myList”的最大元素的位置无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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