Showing posts with label descending order. Show all posts
Showing posts with label descending order. Show all posts

Tuesday, 6 April 2021

Php: rsort: Sort array contents in descending order

‘rsort’ function return the elements in descending order (in place, affect the original array).

 

Syntax

rsort($array_name);

 

Example

rsort($arr);

 

Find the below working example.

 

array_reverse_sort_demo.php

#!/usr/bin/php

<?php

    $arr = array(22, 31, -5, 77, -98, 18);
    
    echo "Original array : \n";
    print_r($arr);

    rsort($arr);

    echo "Sorted array in descending order : \n";
    print_r($arr);
    
?>

 

Output

$./array_reverse_sort_demo.php 

Original array : 
Array
(
    [0] => 22
    [1] => 31
    [2] => -5
    [3] => 77
    [4] => -98
    [5] => 18
)
Sorted array in descending order : 
Array
(
    [0] => 77
    [1] => 31
    [2] => 22
    [3] => 18
    [4] => -5
    [5] => -98
)

 

 

 

 

Previous                                                    Next                                                    Home

Thursday, 2 January 2020

Sort array in descending order


‘Arrays.sort’ function is used to sort array elements in descending order.

Example
Integer[] arr = { 1, 3, 5, 7, 2, 4, 6, 8, 10 };
Arrays.sort(arr, Collections.reverseOrder());

App.java
package com.sample.app;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;

public class App {

	private static void printElements(Integer[] arr) {
		for (int i : arr) {
			System.out.println(i + " ");
		}
	}

	public static void main(String args[]) throws IOException {
		Integer[] arr = { 1, 3, 5, 7, 2, 4, 6, 8, 10 };
		Arrays.sort(arr, Collections.reverseOrder());
		
		printElements(arr);

	}

}

Run App.java, you will see below messages in console.
10 
8 
7 
6 
5 
4 
3 
2 
1

You may like