UNIHIVE

Study Hub UNIPORT MEG 202

MEG 202 · Basic Software Engineering

Sorting and searching

Linear and binary search, bubble, selection and insertion sort with traces, and faster sorts.

Our notes

2 min read

Searching

  • Linear (sequential) search: check each element in turn until found or the end. Works on unsorted data. Worst case n comparisons.
  • Binary search (sorted data only): compare with the middle element; if the target is smaller, search the left half, else the right half; repeat. Each step halves the range, so at most about log₂ n comparisons: about 20 for a million items.

Example: find 23 in [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] (indices 0-9).

  1. low 0, high 9, mid 4 → 16 < 23 → low = 5.
  2. low 5, high 9, mid 7 → 56 > 23 → high = 6.
  3. low 5, high 6, mid 5 → 23 found at index 5 in 3 comparisons.

Bubble sort

Repeatedly compare adjacent pairs and swap if out of order; the largest value "bubbles" to the end each pass. Stop early if a pass makes no swaps.
Trace on [5, 1, 4, 2, 8]:

  • Pass 1: (5,1) swap → [1,5,4,2,8]; (5,4) swap → [1,4,5,2,8]; (5,2) swap → [1,4,2,5,8]; (5,8) no swap.
  • Pass 2: (1,4) no; (4,2) swap → [1,2,4,5,8]; (4,5) no.
  • Pass 3: no swaps → stop. Result [1, 2, 4, 5, 8].

Selection sort

Find the smallest element and swap it into the first position; then the smallest of the rest into the second; and so on. [29, 10, 14, 37, 13] → [10, 29, 14, 37, 13] → [10, 13, 14, 37, 29] → [10, 13, 14, 37, 29] → [10, 13, 14, 29, 37].

Insertion sort

Take elements one at a time and insert each into its correct place among those already sorted (like sorting playing cards in your hand). Fast for small or nearly sorted lists.

Faster sorts

  • Merge sort: split the list in half, sort each half recursively, merge. Always about n log n steps; needs extra memory.
  • Quicksort: choose a pivot, partition into smaller and larger, sort each part recursively. Average n log n; worst case n² with bad pivots. Widely used in libraries.

Comparison

AlgorithmAverage timeNotes
Bubblen²simple; slow
Selectionn²few swaps
Insertionn²good for nearly sorted data
Mergen log nstable; extra memory
Quickn log nfast in practice

For n = 1,000: n² = 1,000,000 steps, but n log₂ n is about 10,000: a hundred times fewer.

Exams usually ask

  • Trace binary search and say why the data must be sorted.
  • Trace bubble, selection or insertion sort on a short list.
  • Compare sorting algorithms by efficiency.

Common mistake

Applying binary search to unsorted data. It relies on the order to discard half the list at each step.

Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.

Read

Watch

We link to free material and never copy it. Every link was opened by our team before it went up; video data is a rough guide at 360p.

All MEG 202 topics

Report

Sign in to report this. It is free.

Is this your work (a lecturer, author or publisher)? Ask us to take it down.