Free coupon for initial registration

Sort array in ascending order

Contents [hide]

Output

1
2
3


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
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

1
2
3
4
5
let array = [3, 1, 2];
array.sort()
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 = sort @array;
foreach my $item (@sorted_array) {
    print $item."\n";
}

PHP

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

Python

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

Ruby

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