Java program to Sort an Array in descending order - The Coding Shala

Home >> Java Programs >> Sort an Array in Descending order

 In this post, we will learn how to Sort an Array in descending order in Java.

Java program to sort an array in descending order

You have given an array, return the sorted array in descending order.

Example:
Input: {4, 5, -3, 1, 0, -1, 55, 34}
Output: {55, 34, 5, 4, 1, 0, -1, -3}

Approach

Using two loops. (Bubble sort)

Time complexity: O(n^2).

Java Program: 

import java.util.*;

class Solution {
    
    public static void main(String[] args) {
        int[] arr = {4, 5, -3, 1, 0, -1, 55, 34};
        System.out.println("Before sorting array is:");
        for(int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println();
        System.out.println("After sorting in descending order array is:");
        
        //using loops
        for(int i=0; i<arr.length; i++) {
            for(int j=i+1; j<arr.length; j++) {
                //descending order
                if(arr[j] > arr[i]) {
                    //swap the elements
                    int tmp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = tmp;
                }
            }
        }
        
        for(int num : arr) {
            System.out.print(num + " ");
        }
    }
}

Output: 
Before sorting array is:
4 5 -3 1 0 -1 55 34 
After sorting in descending order array is:
55 34 5 4 1 0 -1 -3 


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

New Year Chaos Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala