Browse DevX
Sign up for e-mail newsletters from DevX


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.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

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.
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date