Free coupon for initial registration

Sort array in descending order

Contents [hide]

Output

3
2
1

Code examples


C

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>
int main(void) {
    int i, j, tmp;
    int array[] = {3, 1, 2};
   
    for (i=0; i<sizeof(array)/sizeof(array[0]); i++) {
        for(j=i+1; j<sizeof(array)/sizeof(array[0]); j++) {
            if(array[j] > array[i]) {
                tmp = array[i];
                array[i] = array[j];
                array[j] = tmp;
            }
        }
    }
 
    for(i=0; i < sizeof(array)/sizeof(array[0]); i++) {
        printf("%d\n", array[i]);
    }
}

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
import java.util.Arrays;
import java.util.Collections;
 
public class DescendSortArray {
    public static void main(String[] args) {
        Integer[] myList = new Integer[] { 3, 1, 2 };
        Arrays.sort(myList, Collections.reverseOrder());
 
        for(int i = 0;i<myList.length;i++) {
            System.out.println(myList[i]);
        }
    }
}

JavaScript

1
2
3
4
5
let array = [3, 1, 2];
array.sort(function(a, b){return b-a})
for(let i = 0; i < array.length; i++) {
    console.log(array[i]);
}

Perl

1
2
3
4
5
my @array = (3, 1, 2);
my @sorted_array = reverse sort @array;
foreach my $item (@sorted_array) {
    print $item."\n";
}

PHP

1
2
3
4
5
6
<?php
$array = [3, 1, 2];
rsort($array);
foreach ($array as $item) {
    print $item."\n";
}

Python

1
2
3
4
array = [3, 1, 2]
array.sort(reverse=True)
for item in array:
    print(item)

Ruby

1
2
3
array = [3, 1, 2];
array = array.sort.reverse
array.each { |x| print(x.to_s + "\n") }
Free coupon for initial registration