search
HomeJavajavaTutorialJava program to sort array elements in descending order

Java program to sort array elements in descending order

An array is a collection of the same data type stored in some contiguous memory location. Array is a class in the java.until package that provides predefined sorting in a static manner and has no return value. This is the syntax of Arrays.sort() method mentioned below -

public static void sort(int[] ar, int from_index, int to_index)

In the above syntax, we have

  • ar - Abbreviation of array name

  • from_index - We can use this as an optional parameter where sorting needs to be run.

  • to_index - Optional parameter providing the index of the element.

This is an example

Input :Array = {2, 6, 23, 98, 24, 35, 78}
Output:[98, 78, 35, 24, 23, 6, 2]

Input :Array = {1, 2, 3, 4, 5}
Output:[5, 4, 3, 2, 1]

Today in this article, we will learn how to sort array elements present in a list and rearrange them in descending order using Java environment.

Algorithm for sorting array elements in descending order:-

Here we have written the possible algorithm by which we can sort the array elements in descending order.

  • Step 1 - Get Started

  • Step 2 - Set temperature =0.

  • Step 3 - Declare an array to hold the data.

  • Step 4 - Initialize the array using arr[] ={5, 2, 8, 7, 1}.

  • Step 5 - Print "Elements of Original Array"

  • Step 6 - Declare a temporary variable to store the element while swapping.

  • Step 7 - Use two for loops to achieve the same purpose.

  • Step 8 - Repeat i

  • Step 9 - Use the first for loop to save the element and iterate through all elements.

  • Step 10 - if(arr[i]

    temporary= arr[i]

    arr[i]=arr[j]

    arr[j]=temp

  • Step 11 - Use a second for loop to compare with the remaining elements

  • Step 12 - Print new line.

  • Step 13 - Sort elements by comparison and exchange.

  • Step 14 - Iterate using for(i=0;i

  • Step 15 - Display the updated array as PRINT arr[i].

  • Step 16 - Stop

Syntax for sorting array elements in descending order

import java.util.*;
class Tutorialspoint071001 {
   public static void main(String[] args){
     // Initializing the array for the process
     Integer array[] = { 1, 2, 7, 16, 5,6 };

     // Sorting the array in a descending order
     Arrays.sort(array, Collections.reverseOrder());

     // Printing the elements after the process run
     System.out.println(Arrays.toString(array));
   }
}

Method to follow

  • Method 1 - Java program to sort elements in descending order

  • Method 2 - Java program to sort elements in descending order using temp function

  • Method 3 - Java program to sort elements in descending order using common logic

Java program to sort elements in descending order

In this Java code, we try to build a logic for the process of sorting array elements in descending order.

Example 1

import java.util.*;
public class tutorialspoint {
   public static void main(String[] args){

      // Initializing the array for the process run
      int array[] = { 1, 2, 3, 7, 5, 16 };

      // Sorting the array in ascending order if needed
      Arrays.sort(array);

      // Reversing the array for the main process
      reverse(array);

      // Printing the elements from the array
      System.out.println(Arrays.toString(array));
   }
   public static void reverse(int[] array){

      // Length of the array is mentioned here
      int n = array.length;

      // Run the process again. Swapping the first half elements with last half elements
      for (int i = 0; i < n / 2; i++) {

         // Storing the first half elements in a temp manner
         int temp = array[i];

         // Assigning the first half to the last half to get result
         array[i] = array[n - i - 1];

         // Assigning the last half to the first half to get the result
         array[n - i - 1] = temp;
      }
   }
}

Output

[16, 7, 5, 3, 2, 1]

Java program to sort elements in descending order using temp function

In this Java code, we can use the temp function to build a logic to sort the elements in the array in descending order.

Example 2

import java.util.Scanner;
public class Descendingtutorialspountrddarb{
   public static void main(String[] args) {
      int n, temp;
      Scanner s = new Scanner(System.in);
      System.out.print("Enter no. number of elements you want in the array---->:");
      n = s.nextInt();
      int a[] = new int[n];
      System.out.println("Enter all the elements here now to run the code further ----> :");
      for (int i = 0; i < n; i++) {
         a[i] = s.nextInt();
      }
      for (int i = 0; i < n; i++) {
         for (int j = i + 1; j < n; j++) {
            if (a[i] < a[j]) {
               temp = a[i];
               a[i] = a[j];
               a[j] = temp;
            }
         }
      }
      System.out.print("Descending Order Output Is Here. Have A Look!:");
      for (int i = 0; i < n - 1; i++) {
         System.out.print(a[i] + ",");
      }
      System.out.print(a[n - 1]);
   }
}

Output

Enter no. number of elements you want in the array---->:7
Enter all the elements here now to run the code further ----> :
1
2
3
16
4
5
6
Descending Order Output Is Here. Have A Look!:16,6,5,4,3,2,1

Use common logic to sort elements in descending order

In this Java code, we have written a logic to sort the elements in an array in descending order by using some common functions.

Example 3

public class Tutorialspoint {
   public static void main(String[] args) {
      //Initialize array for the process 
      int [] arr = new int [] {16, 2022, 2001, 1997, 7}; 
      int temp = 0;

      //Displaying elements of an original array to go further
      System.out.println("Elements of original array are ---->: ");
      for (int i = 0; i < arr.length; i++) { 
         System.out.print(arr[i] + " ");
      }

      //Sort the array in descending order. Please go further
      for (int i = 0; i < arr.length; i++) { 
         for (int j = i+1; j < arr.length; j++) { 
            if(arr[i] < arr[j]) {
               temp = arr[i];
               arr[i] = arr[j];
               arr[j] = temp;
            } 
         } 
      }
      System.out.println();
      //Displaying elements of array after sorting process done.
      System.out.println("Elements of array sorted in descending order is here ---->: ");
      for (int i = 0; i < arr.length; i++) { 
         System.out.print(arr[i] + " ");
      }
   }
}

Output

Elements of original array are ---->: 
16 2022 2001 1997 7 
Elements of array sorted in descending order is here ---->: 
2022 2001 1997 16 7

in conclusion

We have learned about the sorting of array elements in detail. Today we use various sorting methods to solve this problem through the grammar and algorithm mentioned above. Hopefully, through this article you have gained a broad understanding on how to sort array elements in descending order using Java environment.

The above is the detailed content of Java program to sort array elements in descending order. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

Is Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksIs Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksMay 13, 2025 am 12:03 AM

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

Demystifying the JVM: Your Key to Understanding Java ExecutionDemystifying the JVM: Your Key to Understanding Java ExecutionMay 13, 2025 am 12:02 AM

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Is java still a good language based on new features?Is java still a good language based on new features?May 12, 2025 am 12:12 AM

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

What Makes Java Great? Key Features and BenefitsWhat Makes Java Great? Key Features and BenefitsMay 12, 2025 am 12:11 AM

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Top 5 Java Features: Examples and ExplanationsTop 5 Java Features: Examples and ExplanationsMay 12, 2025 am 12:09 AM

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.