Java program to Sort an Array in descending order - The Coding Shala
Home >> Java Programs >> Sort an Array in Descending order
Other Posts You May Like
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
- Java Program to Sort an array in ascending order
- Merge Sort Algorithm
- Quick Sort Algorithm
- Insertion Sort Algorithm
- Java Program to Multiply two numbers
Comments
Post a Comment