devxlogo

Sorting and Searching

Sorting and Searching

he Java 2 Collections Framework includes a set of static methods forsorting and searching lists and arrays. The java.util.Collectionsclass contains methods for manipulating instances of List and thejava.util.Arrays class contains methods for manipulating arrays ofobjects and primitive types.

Each class supports a set of sort()methods and binarySearch() methods. The binarySearch() method willperform a binary search on the List or array and return the index ofthe 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 bydefault. You can define a Comparator implementation thatwill change the sort order.

The example below generates an arrayof random integers between 0 and 99, sorts it, prints it out, and thensearches 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("	" + Arrays.binarySearch(numbers, numbers[50]));  }}
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist