
he
Java 2 Collections Framework includes a set of static methods for
sorting and searching lists and arrays. The java.util.Collections
class contains methods for manipulating instances of List and the
java.util.Arrays class contains methods for manipulating arrays of
objects and primitive types.
Each class supports a set of sort()
methods and binarySearch() methods. The binarySearch() method will
perform a binary search on the List or array and return the index of
the item found or a negative value if the item is not present.
However, the List or array must already be sorted in ascending order.
The sort() methods will sort a list or array into ascending order by
default. You can define a Comparator implementation that
will change the sort order.
The example below generates an array
of random integers between 0 and 99, sorts it, prints it out, and then
searches for a value, printing out its array index.
import java.util.*;
public class Sort {
public static void main(String[] args) {
int i;
int[] numbers = new int[100];
Random random = new Random(System.currentTimeMillis());
for(i = 0; i < numbers.length; ++i)
numbers[i] = random.nextInt(numbers.length);
Arrays.sort(numbers);
for(i = 0; i < numbers.length; ++i)
System.out.println(numbers[i]);
System.out.println("Index of " + numbers[50] + ":");
// Should be <=50 depending on duplicates
System.out.println("\t" + Arrays.binarySearch(numbers, numbers[50]));
}
}