Stop 10 · Data Structures & Algorithms in JavaTopics · 5/11

Sorting & Binary Search

Part of the Java Roadmap

In short

Sorted data is powerful: you can search it in a handful of steps, spot duplicates next to each other and merge it cheaply. Knowing how sorts work, and when to just call Arrays.sort, is core interview ground.

Know how bubble, insertion, merge and quick sort work, and how binary search finds items in sorted data in O(log n). In practice, Arrays.sort() and Collections.sort() handle sorting for you.

The jaadu splits a huge dictionary open right in the middle, with a bookmark already marking the next half to check.

Think of it like this

Finding a word in a dictionary

Looking for 'mango' in a thick dictionary, you don't read from page one. You open the middle, see 'kite', and know mango is in the right half. You split again and again. A thousand pages take about ten flips. That halving is binary search, and it only works because the dictionary is sorted.

Watch it happen

Binary search for 37

5
0
lo
12
1
18
2
23
3
37
4
41
5
56
6
72
7
hi

1/4The array is sorted. lo = 0, hi = 7.

The big ideas

What you need to know

Know the classics

Bubble and insertion sort are O(n²). Merge sort is O(n log n) and stable. Quick sort is O(n log n) on average, O(n²) at worst.

What Java uses

Arrays.sort on primitives uses dual-pivot quicksort. On objects and in List.sort it uses TimSort, which is stable.

Comparators

Comparator.comparingInt(Student::marks).reversed().thenComparing(Student::name) sorts by marks, then by name.

Binary search is O(log n)

It needs sorted data. Use lo + (hi - lo) / 2 for mid, and think carefully about lo <= hi.

See it in code

Walk through the code

java
1import java.util.ArrayList;2import java.util.Arrays;3import java.util.Comparator;4import java.util.List;5 6public class SortSearch {7    record Student(String name, int marks) {}8 9    static int binarySearch(int[] a, int target) {10        int lo = 0, hi = a.length - 1;11        while (lo <= hi) {12            int mid = lo + (hi - lo) / 2;   // avoids int overflow13            if (a[mid] == target) return mid;14            if (a[mid] < target) lo = mid + 1;15            else hi = mid - 1;16        }17        return -1;18    }19 20    public static void main(String[] args) {21        int[] marks = {72, 18, 41, 5, 37, 56, 23, 12};22        Arrays.sort(marks);                           // O(n log n)23        System.out.println(binarySearch(marks, 37));  // 424 25        List<Student> students = new ArrayList<>(List.of(26            new Student("Dev", 78), new Student("Bhavna", 91), new Student("Ananya", 91)));27        students.sort(Comparator.comparingInt(Student::marks).reversed()28                .thenComparing(Student::name));29        System.out.println(students);  // Ananya (91), Bhavna (91), Dev (78)30    }31}

1/4Search the range lo to hi. Computing mid this way never overflows, even for huge arrays.

A hand-written binary search, plus the library sorts you will use in real code.

Save yourself the pain

Common mistakes

Oops

int mid = (lo + hi) / 2;

Do this instead

For very large indexes lo + hi can overflow int. lo + (hi - lo) / 2 is the safe habit.

Oops

Using a comparator like (a, b) -> a.marks() - b.marks().

Do this instead

Subtraction can overflow for large values. Use Integer.compare or Comparator.comparingInt.

Oops

Running binary search on an unsorted array.

Do this instead

Sort it first, or use a HashSet if you only need membership checks.

Your mission

Sort and search drills

~60 min

Quick check

About how many comparisons does binary search need on 10 lakh sorted numbers?

Go deeper

  1. 1Implement merge sort and quick sort by hand.
  2. 2Implement binary search and solve 3 binary search problems.
  3. 3Learn which sorts are stable and their time complexities.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge