How do i sort array elements into ascending order?
A:
Arrays.sort(...)
http://java.sun.com/j2se/1.4.2/docs/api/java/util/Arrays.html
Jarle Hansen
2010-05-10 07:38:45
+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
2010-05-10 07:40:35
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
2010-05-10 07:43:33