Sub topic 10
Sorting and Searching Arrays
Java provides tools for putting array values in order and finding a value in an ordered array. These tools are useful when you need to look through the same data more than once.
An array is a fixed-size sequence of values. Each value is an element. An index is the number that identifies an element’s position, starting at 0.
In this chapter, you will use methods from java.util.Arrays. A method is a named action that Java can run.
Sort a copy, then search it
Arrays.sort puts elements in ascending order: from smallest to largest. It changes the array passed to it.
If you need to keep the original order, make a copy first. Then sort and search the copy.
Save this program as Main.java:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] original = {3, 1, 2};
int[] copy = Arrays.copyOf(original, original.length);
Arrays.sort(copy);
int index = Arrays.binarySearch(copy, 2);
System.out.println("Original: " + Arrays.toString(original));
System.out.println("Sorted copy: " + Arrays.toString(copy));
System.out.println("Index of 2: " + index);
}
}Compile and run it with these commands:
javac Main.java
java MainThe output is:
Original: [3, 1, 2]
Sorted copy: [1, 2, 3]
Index of 2: 1The import line lets the program use the short name Arrays. The call to Arrays.copyOf makes a separate array. Arrays.toString makes the contents easy to print.
After sorting, the value 2 is at index 1 in copy. Its index in the original array is different. Always interpret a search result as an index into the array you searched.
Each later program in this chapter is complete. To run one, replace the contents of Main.java with that program, then use the same two commands.
How binary search works
A binary search finds a value by checking the middle of an ordered range. If the target is smaller than the middle value, the search continues in the lower part. If it is larger, the search continues in the upper part. Each step rules out part of the array.
The array must already be sorted in the order used by the search. Arrays.binarySearch does not sort it for you. If the array is not sorted correctly, the result is not reliable.
Binary search can save work when you search a large, sorted array many times. Sorting also takes work, though. If you only need one search and the data is not sorted, checking the elements one by one may be simpler.
Read the search result
When Arrays.binarySearch finds a value, it returns an index of that value. An index can be 0, so test for a result greater than or equal to 0.
When it does not find the value, it returns a negative number. That number describes the insertion point: the index where the value could be placed to keep the array sorted. The method does not insert the value.
To get the insertion point from a negative result, use:
insertionPoint = -result - 1
Try this program:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 40};
int[] targets = {10, 30, 50, 5};
for (int target : targets) {
int result = Arrays.binarySearch(numbers, target);
if (result >= 0) {
System.out.println(target + ": found at " + result);
} else {
int insertionPoint = -result - 1;
System.out.println(
target + ": not found; insertion point " + insertionPoint
);
}
}
}
}The output is:
10: found at 0
30: not found; insertion point 2
50: not found; insertion point 3
5: not found; insertion point 0For example, 30 belongs between 20 and 40, at index 2. The search returns -3, and -(-3) - 1 gives 2.
An insertion point can equal the array’s length. That means the missing value belongs after every existing element. It is not an index you can use to read an existing element.
Repeated values
If the array contains a value more than once, binary search can return the index of any matching element. It does not promise the first or last match.
For example, searching {1, 2, 2, 2, 3} for 2 can return 1, 2, or 3. If you need every match, one option is to find a match and then check the neighboring elements.
Sort and search part of an array
Sometimes only part of an array needs to be sorted. The range versions of Arrays.sort and Arrays.binarySearch take two indexes:
- The start index is included.
- The end index is excluded.
For example, the range from 1 to 4 contains indexes 1, 2, and 3.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] values = {99, 30, 10, 20, 77};
Arrays.sort(values, 1, 4);
int found = Arrays.binarySearch(values, 1, 4, 20);
int missing = Arrays.binarySearch(values, 1, 4, 25);
System.out.println(Arrays.toString(values));
System.out.println("Index of 20: " + found);
System.out.println("Result for 25: " + missing);
}
}The output is:
[99, 10, 20, 30, 77]
Index of 20: 2
Result for 25: -4The values 99 and 77 stay where they are because they are outside the sorted range. The index returned for 20 is 2 in the whole array, not 1 within the range.
The result for 25 is -4. Its insertion point is 3, between 20 and 30.
Only the selected range is sorted here. Do not use a whole-array binary search on values: the whole array is not in ascending order. Search the sorted range instead.
Sort and search strings
A string is a sequence of characters, such as "apple". Arrays.sort can sort a String[] as well as an int[].
By default, Java compares strings character by character. This comparison is case-sensitive: it treats uppercase and lowercase letters differently. For example, "Banana" comes before "apple" in the default order.
You can choose a different comparison rule. A comparator is an object that tells Java how to compare values. String.CASE_INSENSITIVE_ORDER is a built-in comparator that ignores letter case when comparing strings.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] words = {"pear", "apple", "Banana"};
Arrays.sort(words, String.CASE_INSENSITIVE_ORDER);
int index = Arrays.binarySearch(
words, "APPLE", String.CASE_INSENSITIVE_ORDER
);
System.out.println(Arrays.toString(words));
System.out.println("Match for APPLE: " + index);
}
}The output is:
[apple, Banana, pear]
Match for APPLE: 0The search finds "apple" even though the target is "APPLE". Under this comparison rule, their letters match without regard to case.
Use the same comparison rule for both sorting and searching. If you sort with String.CASE_INSENSITIVE_ORDER, pass it to binarySearch too. Otherwise, the search may assume an order that the array does not have.
Do not use null as a string element when relying on the default string comparison. null means there is no string to compare, so a comparison involving it can fail.
Common mistakes
| Mistake | Safer approach |
|---|---|
| Search an unsorted array with `binarySearch` | Sort it first, or check its elements one by one. |
| Test `result > 0` for a match | Test `result >= 0`; index `0` is a valid match. |
| Treat every negative result as `-1` | Decode the insertion point with `-result - 1`. |
| Sort an array that must keep its order | Copy it, then sort the copy. |
| Sort and search with different rules | Use the same ordering for both operations. |
| Search the whole array after sorting only a range | Search the range that is sorted. |
Also check the order after changing elements. If an update puts a value out of order, sort the array again before using binary search.
Practice
Exercise
After sorting {8, 3, 5}, what index does binary search return for 5?
Show answer
It returns 1. The sorted array is {3, 5, 8}, and 5 is at index 1.
Exercise
A search for 7 in {2, 4, 9} returns a negative result. What are the insertion point and the result?
Show answer
The insertion point is 2, between 4 and 9. The result is -3, because -(2) - 1 is -3.
Exercise
You sort a string array with String.CASEINSENSITIVEORDER. What rule should you pass to binarySearch?
Show answer
Pass String.CASEINSENSITIVEORDER to the search too, so it uses the same order.