Arrays.sort with Custom Range
What you'll learn: How to sort only a specific portion of an array instead of the entire thing.
Why Sort Just Part of an Array?
Sometimes you don't want to sort an entire array—maybe you only need the first few elements organized, or perhaps you want to leave certain sections untouched. Java's Arrays.sort method offers an overloaded version that lets you specify exactly which slice of the array to sort.
The Syntax
Instead of sorting the whole array with Arrays.sort(array), you can provide start and end indices:
Arrays.sort(array, fromIndex, toIndex);
- fromIndex: The starting index (inclusive) where sorting begins
- toIndex: The ending index (exclusive) where sorting stops
The range follows Java's typical half-open interval pattern: [fromIndex, toIndex).
Example in Action
int[] numbers = {50, 20, 90, 10, 60, 30};
Arrays.sort(numbers, 1, 4);
// Sorts only indices 1, 2, 3 (elements: 20, 90, 10)
// Result: {50, 10, 20, 90, 60, 30}
Notice that 50 at index 0 and 60, 30 at indices 4 and 5 remain in their original positions. Only the middle section gets sorted.
Think of It Like This
Imagine organizing books on a shelf, but only straightening the middle three shelves while leaving the top and bottom shelves exactly as they are. You're applying order to a specific region while preserving the rest.
Watch Your Boundaries
The toIndex must not exceed the array's length, and fromIndex must be less than toIndex. Otherwise, you'll encounter exceptions.
Key Takeaway: Arrays.sort(array, fromIndex, toIndex) sorts only the elements between fromIndex (inclusive) and toIndex (exclusive), leaving the rest of the array unchanged.