繁体   English   中英

按升序对整数排序-Java

[英]Sort integer in Ascending Order - Java

我需要帮助,了解如何对数字进行排序。 到目前为止,我想出的是以下内容,但没有奏效。 您能指出错误并告诉我该怎么做吗?

我看到有些人使用java.util.Arrays 你能告诉我它的功能吗?

import static java.lang.System.*;
import java.util.*;

    public class Lab07v2_Task10{
    public static void main (String[] args){
            Scanner orcho = new Scanner (in);
            int quantity = 5;
            int[] myArray = new int [quantity];
            out.println("Please enter 5 numbers");

            for(int count = 0; count<myArray.length; count++){
                myArray[count] = orcho.nextInt();
            }

            int maxSoFar = myArray[0];

            for(int count = myArray.length-1; count>=0; count--){
                if(myArray[count] > maxSoFar){
                maxSoFar = myArray[count];
            }
            out.println(maxSoFar);
       }
    }
}   

没有解决方案。 这个想法是采取几个步骤,做一个循环。 并假设您在中间。 第一部分已经排序,其余部分将要完成。

然后针对已排序的内容处理当前元素。

int maxSoFar = myArray[0];
for (int i = 1; i < myArray.length; i++) {
    // The array 0, ..., i-1 is sorted
    if (myArray[i] >= maxSoFar) {
        // Still sorted
        maxSoFar = myArray[i];
    } else {
        // myArray[i] must be shifted left
        ...
    }
    // Now the array 0, ..., i is sorted
}

这是一个通用的技巧:假设部分已经完成,迈出一小步,然后继续。

java.util.Arrays.sort(int[])方法将指定的int 数组按升序排序。

试试看..

// sorting array
  java.util.Arrays.sort(myArray);

   // let us print all the elements available in list
   System.out.println("The sorted int array is:");
   for (int number : myArray) {
   System.out.println("Number = " + number);
   }
   }

Arrays.sort是一种方法,它是java.util包中可用的实用程序方法。

其中Arrays是系统定义的Utility类,其中包含mehtod sort(int[])int[] (数组)作为参数,并对数组进行排序后,它会重新分配Array。

有关更多详细信息,请参见此处官方Java文档。

程序现在的运行方式:它将打印5个数字,并且打印的数字是该迭代中找到的最高数字。

您希望它的工作方式:从最低到最高对5个数字进行排序。 然后打印这5个数字。 这是程序中冒泡排序的实现:

for(int i = 0; i< myArray.length; i++){
        for(int j = 0; j < myArray.length-1; j++){
            if(myArray[j] > myArray[j+1]){ //if the current number is less than the one next to it
                int temp = myArray[j]; //save the current number 
                myArray[j] = myArray[j+1]; //put the one next to it in its spot
                myArray[j+1] = temp; //put the current number in the next spot
            }
        }
    }

这可能是最容易理解的一种。 基本上,要对数组长度进行多次遍历,然后对数字进行梳理,并尽可能增加下一个最高的数字。

完成排序后,您可以打印数字。

暂无
暂无

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

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