简体   繁体   English

java中的升序和降序数

[英]Ascending and Descending Number Order in java

I'm doing an ascending and descending order number in java and here's my code: 我在java中执行升序和降序编号,这是我的代码:

System.out.print("Enter How Many Inputs: ");
int num1 = Integer.parseInt(in.readLine());
int arr[] = new int[num1];

for (int i = 0; i<num1; i++) {
    System.out.print("Enter Value #" + (i + 1) + ":");
    arr[i] =Integer.parseInt(in.readLine());
}

System.out.print("Numbers in Ascending Order:" );

for(int i = 0; i < arr.length; i++) {
    Arrays.sort(arr);
    System.out.print( " " +arr[i]);
}

System.out.println(" ");
System.out.print("Numbers in Descending Order: " );

Currently, the code generates the following: 目前,代码生成以下内容:

Enter How Many Inputs: 5
Enter Value #1:3
Enter Value #2:5
Enter Value #3:6
Enter Value #4:11
Enter Value #5:2
Numbers in Ascending Order: 2 3 5 6 11 
Numbers in Descending Order: 

So, the Arrays.sort(arr) call seems to work - but I'm looking for a similarly simple way to provide the descending sort, and can't find it in the documentation. 因此, Arrays.sort(arr)调用似乎有效 - 但我正在寻找一种类似的简单方法来提供降序排序,并且无法在文档中找到它。 Any ideas? 有任何想法吗?

Three possible solutions come to my mind: 我想到了三种可能的解决方案:

1. Reverse the order: 1.撤销订单:

//convert the arr to list first
Collections.reverse(listWithNumbers);
System.out.print("Numbers in Descending Order: " + listWithNumbers);

2. Iterate backwards and print it: 2.向后迭代并打印出来:

Arrays.sort(arr);
System.out.print("Numbers in Descending Order: " );
for(int i = arr.length - 1; i >= 0; i--){
  System.out.print( " " +arr[i]);
}

3. Sort it with "oposite" comparator: 3.用“oposite”比较器对其进行排序:

Arrays.sort(arr, new Comparator<Integer>(){
   int compare(Integer i1, Integer i2) {
      return i2 - i1;
   }
});
// or Collections.reverseOrder(), could be used instead
System.out.print("Numbers in Descending Order: " );
for(int i = 0; i < arr.length; i++){
  System.out.print( " " +arr[i]);
}
public static void main(String[] args) {
          Scanner input =new Scanner(System.in);
          System.out.print("enter how many:");
         int num =input.nextInt();
    int[] arr= new int [num];
    for(int b=0;b<arr.length;b++){
   System.out.print("enter no." + (b+1) +"=");
   arr[b]=input.nextInt();
    }

    for (int i=0; i<arr.length;i++) {
        for (int k=i;k<arr.length;k++) {

        if(arr[i] > arr[k]) {

        int temp=arr[k];
        arr[k]=arr[i];
        arr[i]=temp;
        }
            }

    }
    System.out.println("******************\n output\t accending order");


    for (int i : arr){
        System.out.println(i);
    }
}
}

Why are you using array and bothering with the first question of number of wanted numbers ? 你为什么要使用array并打扰想要数字的第一个问题?

Prefer an ArrayList associated with a corresponding comparator: 首选与相应比较器关联的ArrayList

List numbers = new Arraylist();
//add read numbers (int (with autoboxing if jdk>=5) or Integer directly) into it

//Initialize the associated comparator reversing order. (since Integer implements Comparable)
Comparator comparator = Collections.reverseOrder();

//Sort the list
Collections.sort(numbers,comparator);

you can make two function one for Ascending and another for Descending the next two functions work after convert array to List 你可以为升序创建两个函数,另一个用于将数组转换为List后降序下两个函数

public List<Integer> sortDescending(List<Integer> arr){
    Comparator<Integer> c = Collections.reverseOrder();
    Collections.sort(arr,c);
    return arr;
  }

next function 下一个功能

public List<Integer> sortAscending(List<Integer> arr){   
    Collections.sort(arr);
    return arr;
  }
package pack2;

import java.util.Scanner;

public class group {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner data= new Scanner(System.in);
    int value[]= new int[5];
    int temp=0,i=0,j=0;
    System.out.println("Enter 5 element of array");
    for(i=0;i<5;i++)
    value[i]=data.nextInt();
     for(i=0;i<5;i++)
     {
     for(j=i;j<5;j++)
     {
      if(value[i]>value[j])
      {
       temp=value[i];
       value[i]=value[j];
       value[j]=temp;
      }
     }

     }
      System.out.println("Increasing Order:");
      for(i=0;i<5;i++)
           System.out.println(""+value[i]); 
    }
int arr[] = { 12, 13, 54, 16, 25, 8, 78 };

for (int i = 0; i < arr.length; i++) {
    Arrays.sort(arr);
    System.out.println(arr[i]);
}

Sort the array just as before, but print the elements out in reverse order, using a loop that counts down rather than counting up. 像以前一样对数组进行排序,但是使用一个倒计时而不是向上计数的循环以相反的顺序打印元素。

Also, move the sort out of the loop - you are currently sorting the array over and over again when you only need to sort it once. 此外,将循环移出循环 - 当前只需要对其进行一次排序时,您正在反复对数组进行排序。

                Arrays.sort(arr);
                for(int i = 0; i < arr.length; i++){
                    //Arrays.sort(arr); // not here
                    System.out.print( " " +arr[i]);
                }
                for(int i = arr.length-1; i >= 0; i--){
                    //Arrays.sort(arr); // not here
                    System.out.print( " " +arr[i]);
                }

Just sort the array in ascending order and print it backwards. 只需按升序对数组进行排序并向后打印即可。

Arrays.sort(arr);
for(int i = arr.length-1; i >= 0 ; i--) {
    //print arr[i]
}

You can sort the array first, and then loop through it twice, once in both directions: 您可以先对数组进行排序,然后在两个方向上循环两次:

Arrays.sort(arr); 
System.out.print("Numbers in Ascending Order:" ); 
for(int i = 0; i < arr.length; i++){ 
  System.out.print( " " + arr[i]); 
} 
System.out.print("Numbers in Descending Order: " ); 
for(int i = arr.length - 1; i >= 0; i--){ 
  System.out.print( " " + arr[i]); 
} 
Arrays.sort(arr, Collections.reverseOrder());
for(int i = 0; i < arr.length; i++){
    System.out.print( " " +arr[i]);
}

And move Arrays.sort() out of that for loop.. You are sorting the same array on each iteration.. 并将Arrays.sort()移出for循环..你在每次迭代时对相同的数组进行排序..

You could take the ascending array and output in reverse order, so replace the second for statement with: 您可以采用相反的顺序获取升序数组和输出,因此将第二个for语句替换为:

for(int i = arr.length - 1; i >= 0; i--) {
    ...
}

If you have Apache's commons-lang on the classpath, it has a method ArrayUtils.reverse(int[]) that you can use. 如果你在类路径上有Apache的commons-lang,它有一个你可以使用的方法ArrayUtils.reverse(int [])。

By the way, you probably don't want to sort it in every cycle of the for loop. 顺便说一句,您可能不希望在for循环的每个循环中对其进行排序。

use reverse for loop to print in descending order, 使用reverse for循环以降序打印,

for (int i = ar.length - 1; i >= 0; i--) {
    Arrays.sort(ar);
    System.out.println(ar[i]);
}

I have done it in this manner (I'm new in java(also in programming)) 我是以这种方式完成的(我是java的新手(也是编程))

import java.util.Scanner;

public class SortingNumbers { public class SortingNumbers {

public static void main(String[] args) {
    Scanner scan1=new Scanner(System.in);
    System.out.print("How many numbers you want to sort: ");
    int a=scan1.nextInt();

    int i,j,k=0; // i and j is used in various loops.
    int num[]=new int[a];
    int great[]= new int[a];    //This array elements will be used to store "the number of being greater."  

    Scanner scan2=new Scanner(System.in);
    System.out.println("Enter the numbers: ");

    for(i=0;i<a;i++)    
        num[i] = scan2.nextInt();

    for (i=0;i<a;i++) {
        for(j=0;j<a;j++) {
            if(num[i]>num[j])   //first time when executes this line, i=0 and j=0 and then i=0;j=1 and so on. each time it finishes second for loop the value of num[i] changes.
                k++;} 
    great[i]=k++;  //At the end of each for loop (second one) k++ contains the total of how many times a number is greater than the others.
    k=0;}  // And then, again k is forced to 0, so that it can collect (the total of how many times a number is greater) for another number.

    System.out.print("Ascending Order: ");
    for(i=0;i<a;i++)
        for(j=0;j<a;j++)
            if(great[j]==i) System.out.print(num[j]+","); //there is a fixed value for each great[j] that is, from 0 upto number of elements(input numbers).
    System.out.print("Discending Order: ");
    for(i=0;i<=a;i++)
        for(j=0;j<a;j++)
            if(great[j]==a-i) System.out.print(+num[j]+",");
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM