降序排列数组

Contents

输出结果

3
2
1

程式码


C

#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

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

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

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

PHP

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

Python

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

Ruby

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