数组升序排序

Contents

输出结果

1
2
3


程式码


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; 
public class AscendSortArray {
    public static void main(String[] args) {
        int[] myList = {3, 1, 2};
	    Arrays.sort(myList);
        for(int i = 0;i<myList.length;i++) {
            System.out.println(myList[i]);
        }
    }
}

JavaScript

let array = [3, 1, 2];
array.sort()
for(let i = 0; i < array.length; i++) {
	console.log(array[i]);
}

Perl

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

PHP

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

Python

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

Ruby

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