如何以升序排列 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));
}
}输出
你还可以使用 Arrays 类中的 sort() 方法对数组进行排序。
int[] myArray = {12, 56, 78, 90, 123, 75, 897};
Arrays.sort(myArray);
System.out.println(Arrays.toString(myArray));
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP