I'm doing an ascending and descending order number in java and here's my code:
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. Any ideas?
Using the sort() Method util package that provides sort() method to sort an array in ascending order. It uses Dual-Pivot Quicksort algorithm for sorting.
sort() method is present in java. util. Collections class. It is used to sort the elements present in the specified list of Collection in ascending order.
Answer: In general terms, Ascending means smallest to largest, 0 to 9, and/or A to Z and Descending means largest to smallest, 9 to 0, and/or Z to A. Ascending order means the smallest or first or earliest in the order will appear at the top of the list: For numbers or amounts, the sort is smallest to largest.
Three possible solutions come to my mind:
1. Reverse the order:
//convert the arr to list first
Collections.reverse(listWithNumbers);
System.out.print("Numbers in Descending Order: " + listWithNumbers);
2. Iterate backwards and print it:
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:
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With