tags:

views:

94

answers:

3

How do i sort array elements into ascending order?

+3  A: 

Your elements must be Comparable or use a Comparator that compares the objects in the array. This is needed, as Java doesn't know by which fields you want to compare two objects. An OK example seems to be the following: http://lkamal.blogspot.com/2008/07/java-sorting-comparator-vs-comparable.html

After that you can use Array.sort()

Indrek
A: 

You use an overload of sort from java.util.Arrays that works in your case; you may need to implement Comparable or provide a custom Comparator, or neither if your type is a primitive/already defines its own natural ordering.

    int[] arr = { 3, 1, 5, 7, 2, -5 };
    Arrays.sort(arr);
    System.out.println(Arrays.toString(arr));
    // prints "[-5, 1, 2, 3, 5, 7]"

See also

polygenelubricants