advertisement
Login | Register   
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Partners & Affiliates
advertisement
advertisement
advertisement
advertisement
Average Rating: 3/5 | Rate this item | 20 users have rated this item.
 

Sorting and Searching

The Java 2 Collections Framework includes a set of static methods for sorting and searching lists and arrays. Java Pro Danny Savarese provides sample code that demonstrates the basics.  


advertisement
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]));
}
}
   
Daniel F. Savarese holds a B.S. in astronomy and an M.S. in computer science, both from the University of Maryland, College Park. He is the author of the OROMatcher regular expression library for Java. Reach him here.
Please rate this item (5=best)
 1  2  3  4  5
advertisement