Java 实例 按升序排序数组

来源:这里教程网 时间:2026-02-17 20:16:51 作者:

在这个 java 教程中,我们使用临时变量和嵌套for循环按升序对数组进行排序。我们使用Scanner类来获取用户的输入。

Java 示例:按升序排序数组

在该程序中,要求用户输入他想要输入的元素的数量。根据输入,我们声明了一个int数组,然后我们接受用户输入的所有数字并将它们存储在数组中。

一旦我们将所有数字存储在数组中,我们就会使用嵌套for循环对它们进行排序。

import java.util.Scanner;public class JavaExample {    public static void main(String[] args)     {        int count, temp;        //User inputs the array size        Scanner scan = new Scanner(System.in);        System.out.print("Enter number of elements you want in the array: ");        count = scan.nextInt();        int num[] = new int[count];        System.out.println("Enter array elements:");        for (int i = 0; i < count; i++)         {            num[i] = scan.nextInt();        }        scan.close();        for (int i = 0; i < count; i++)         {            for (int j = i + 1; j < count; j++) {                 if (num[i] > num[j])                 {                    temp = num[i];                    num[i] = num[j];                    num[j] = temp;                }            }        }        System.out.print("Array Elements in Ascending Order: ");        for (int i = 0; i < count - 1; i++)         {            System.out.print(num[i] + ", ");        }        System.out.print(num[count - 1]);    }}

输出:

Java 实例 按升序排序数组

相关推荐