如何在 Java 中对随机数数组进行排序?


要对 Java 中的数组进行排序,你需要比较数组中的每个元素和所有剩余元素,并验证它们是否更大,如果更大则交换它们。

要做到这一点,一种解决方案是使用两个循环(嵌套循环),其中内循环从 i+1 开始(其中 i 是外循环的变量),以避免比较中的重复。

示例

 实时演示

import java.util.Arrays;
import java.util.Scanner;

public class ArrayInOrder {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array that is to be created::");
      int size = sc.nextInt();
      int[] myArray = new int[size];
      System.out.println("Enter the elements of the array ::");
   
      for(int i = 0; i<size; i++) {
         myArray[i] = sc.nextInt();
      }

      for(int i = 0; i<size-1; i++) {
         for (int j = i+1; j<myArray.length; j++) {
            if(myArray[i] > myArray[j]) {
               int temp = myArray[i];
               myArray[i] = myArray[j];
               myArray[j] = temp;
            }
         }
      }
      System.out.println(Arrays.toString(myArray));
   }
}

输出

Enter the size of the array that is to be created ::
6
Enter the elements of the array ::
54
63
14
78
2
3
[2, 3, 14, 54, 63, 78]

更新时间:2019 年 7 月 30 日

2K+ 浏览量

开启你的职业生涯

完成课程,获得认证

开始学习
广告
© . All rights reserved.