Phase 7 of 20 · Topic 7.4

Arrays Utility Class (Dual-Pivot Quicksort & Binary Search)

1Concept

`java.util.Arrays` offers essential static algorithms: `Arrays.sort()` uses Vladimir Yaroslavskiy's Dual-Pivot Quicksort for primitives (O(N log N) average performance) and TimSort for objects. `Arrays.binarySearch()` performs O(log N) lookups on sorted arrays.

2Architecture Diagram

Unsorted Array: [ 85, 12, 59, 44, 19 ]
       |
       v Arrays.sort() (Dual-Pivot Quicksort)
Sorted Array:   [ 12, 19, 44, 59, 85 ]
       |
       v Arrays.binarySearch(sorted, 44)
Found Index: 2 (O(log N) lookup)

3Code Example

Core Java
import java.util.Arrays;

public class ArraysUtilityDemo {
    public static void main(String[] args) {
        int[] data = {85, 12, 59, 44, 19};
        System.out.println("Original: " + Arrays.toString(data));

        // Dual-Pivot Quicksort
        Arrays.sort(data);
        System.out.println("Sorted:   " + Arrays.toString(data));

        // Binary Search (Array MUST be pre-sorted)
        int target = 44;
        int index = Arrays.binarySearch(data, target);
        System.out.println("Binary search for " + target + " found at index: " + index);

        // Array Equality Verification
        int[] copy = Arrays.copyOf(data, data.length);
        System.out.println("Arrays.equals(): " + Arrays.equals(data, copy));
    }
}

4Expected Output

Original: [85, 12, 59, 44, 19]
Sorted:   [12, 19, 44, 59, 85]
Binary search for 44 found at index: 2
Arrays.equals(): true

5Key Takeaways

  • Binary search requires the array to be strictly sorted; otherwise, the returned index is undefined.
  • If an element is not found, binarySearch returns `-(insertion point) - 1`.
  • For multi-dimensional arrays, use `Arrays.deepEquals()` and `Arrays.deepToString()`.