我在数组中存储了整数值.对数组中的值进行排序和显示



我想创建一个允许用户输入数字x的程序。数字 x 将确定用户输入的整数数。允许用户根据所需的数字输入输入整数并将其存储在数组中。此外,显示数字的降序和索引,而不取消排列原始数组位置中的值。

我已经知道如何按降序对它们进行排序,但这需要在数组中移动值。我不知道如何按降序排列它们,从您输入存储在数组中的值的那一刻起,从索引开始到 0 直到 array.length-1 保留它们的索引。

Example:

Enter a number: 4
Enter 4 numbers:
8  
13  
2
15  
Output:     
15 at array[3]
13 at array[1]
8 at array[0]
2 at array[2]

试试这个:

public static void sortArray () {       
    Scanner in = new Scanner(System.in);
    System.out.print("Enter a number: ");
    int n = in.nextInt();
    int lst[][]  = new int[n][2];
    System.out.println("Enter " + n + " numbers:");
    for(int i=0;i<n;i++) {
        lst[i][0]=in.nextInt();
        lst[i][1]=i;
    }
    for (int i=0;i<n-1;i++)
        for (int j=i+1;j<n;j++)
            if (lst[i][0]<lst[j][0]) {
                int[] tmp = lst[i];
                lst[i]=lst[j];
                lst[j]=tmp;
            }
    for(int i=0;i<n;i++) {
        System.out.println(lst[i][0]+" at array ["+lst[i][1]+"]");
    }                        
}    

最新更新