Find a course

Module 3: AlgorithmsLesson 7 of 1214 min

Searching and Sorting

Compare linear and binary search, see how selection, insertion and merge sort put data in order, and learn why sorted data is so valuable.

Step 1 of 13Learn

The guessing game

"I'm thinking of a number between 1 and 100. After each guess, I'll say higher or lower."

One strategy: guess 1, then 2, then 3... In the worst case you need 100 guesses. A better strategy: guess 50. If the answer is "higher," the number is in 51–100, so guess 75. Each guess cuts the remaining range in half: 100 → 50 → 25 → 13 → 7 → 4 → 2 → 1. You'll always find it in at most 7 guesses.

These are the two classic search algorithms.

Linear search checks items one by one from the start until it finds the target or runs out. It works on any list, sorted or not. For n items, the worst case is n checks.

Binary search works only on sorted data. It checks the middle item. If that's the target, done. If the target is smaller, it throws away the right half; if larger, the left half. Then it repeats on the half that remains. Each step halves the search space, so the worst case is about log₂(n) checks, the number of times you can halve n before reaching 1.

The difference becomes huge as data grows. For a million items, linear search might need a million checks; binary search needs about 20. For a billion, binary search needs about 30.

Step 2 of 13Explore

Linear vs. binary search

The straight line shows the worst-case checks for linear search, which grow one for one with the list size. The readouts compare it with binary search (about log₂ n checks). Increase the list size to see how far apart they get.

02004006008001,000 2004006008001,000
Linear search worst case (checks)
1,000
Binary search worst case (checks)
10
Times faster in the worst case
100 ×

Step 3 of 13Tap to reveal

Binary search, step by step

  1. The setup

    Search for 37 in the sorted list [3, 8, 15, 22, 29, 37, 41, 50, 64]. Keep two markers: low at index 0 and high at index 8. The target, if present, is always somewhere between them.

  2. Check 1

    The middle index is (0 + 8) / 2 = 4, which holds 29. Since 37 is larger than 29, everything from index 0 to 4 can be thrown away. Move low to index 5.

  3. Check 2

    Now the range is indexes 5 to 8. The middle is (5 + 8) / 2 = 6.5, rounded down to 6, which holds 41. Since 37 is smaller, discard indexes 6 to 8 and move high to index 5.

  4. Check 3

    Low and high are both 5. Index 5 holds 37: found it in three checks. Linear search would have needed six. If low ever passes high, the range is empty and the target is not in the list.

Step 4 of 13Practice · Work it out

Using binary search, what is the maximum number of checks needed to find an item in a sorted list of 1,024 items? (Use floor(log₂ n) + 1.)

Step 5 of 13Learn

Sorting: three ways to put things in order

Since binary search needs sorted data, and people love sorted lists (by price, date, name), sorting is one of the most studied problems in computer science. Here are three classic approaches, using the list [5, 2, 8, 1].

Selection sort: find the smallest item and swap it to the front, then find the smallest of the rest and put it second, and so on. [5,2,8,1] → [1,2,8,5] → [1,2,8,5] → [1,2,5,8]. Simple, but for n items it makes about n²/2 comparisons, always.

Insertion sort: build a sorted section on the left, taking each new item and sliding it left into its correct place, like sorting playing cards in your hand. It's slow on big random lists (about n² comparisons in the worst case) but very fast on lists that are already nearly sorted.

Merge sort: divide and conquer. Split the list in half, sort each half (by splitting again, all the way down to single items), then merge the sorted halves by repeatedly taking the smaller front item. Splitting takes about log₂(n) levels, and each level does about n work, so merge sort needs roughly n × log₂(n) steps.

For 1,000,000 items, n² is a trillion operations, while n log₂ n is about 20 million. That's the difference between hours and a fraction of a second.

Step 6 of 13Note

Step 7 of 13Practice · Put in order

Put the steps of merge sort in order for one list.

Drag the items, or use the arrow buttons, to put them in order.

  1. Keep splitting each half until every piece has one item
  2. Finish when one fully sorted list remains
  3. Keep merging sorted pieces into larger sorted pieces
  4. Merge pairs of single items into sorted pairs
  5. Split the list into two halves

Step 8 of 13Compare

Comparing sorting algorithms

AspectSelection sortInsertion sortMerge sort
IdeaRepeatedly select the smallest remaining itemInsert each item into a growing sorted sectionSplit in halves, sort, then merge
Worst-case workAbout n²About n²About n log n
Nearly sorted inputStill about n²Very fast, close to nStill about n log n
Extra memoryVery littleVery littleExtra space for merging

Step 9 of 13Practice · Choose one

A list of 10,000 customer records is already almost in order by date, with just a few new records out of place. Which algorithm from this lesson is likely to be fastest for re-sorting it?

Step 10 of 13Note

Step 11 of 13Practice · Code challenge

Implement linear search. findIndex(list, target) should return the index of the first item equal to target, or -1 if it is not in the list.

Runs in a sandbox in your browser.
  • findIndex([4, 9, 2, 9], 9)
  • findIndex([4, 9, 2], 4)
  • findIndex([4, 9, 2], 7)
  • findIndex([], 1)

Step 12 of 13Practice · True or false

Binary search can be used on any list, whether or not it is sorted.

Step 13 of 13Practice · What would you do?

What would you do?

A school app searches a list of 2,000 students by name every time a teacher types in the search box. The list rarely changes, but each search feels slow on older phones. What is the best improvement?