如何按升序对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));热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短