Chapter 2

Introduction to Searching and Sorting

Meet linear search, bubble sort and insertion sort, and learn when to search a list and when to sort it.

Searching

Searching means finding whether a value (the target) is in a list, and where it is. The simplest method is linear search: start at the first item and check each one in turn until you find the target or reach the end of the list.

Key idea

Linear search works on any list - the items do not need to be sorted. In the worst case it checks every item.

Sorting

Sorting arranges items into order, such as smallest to largest. Two methods you meet first are bubble sort and insertion sort. Both work by comparing items and swapping them when they are in the wrong order.

Bubble sort compares each pair of neighbours and swaps them if needed; after each full pass the largest remaining value has moved to the end.

Example

One pass of bubble sort on [5, 3, 8, 1]: compare 5 and 3 → swap → [3, 5, 8, 1]; compare 5 and 8 → keep; compare 8 and 1 → swap → [3, 5, 1, 8]. The largest value, 8, is now at the end.

Choosing what to do

Search first if you only need to find something; sort first if you need the data in order. Sorted data also lets you use faster search methods (such as binary search) later on.

Remember

  • Linear search checks each item; the list need not be sorted.
  • Bubble sort and insertion sort compare and swap.
  • After one bubble-sort pass, the largest value reaches the end.

Stuck on this topic? A verified JomKelas tutor can walk you through it.

Find a verified tutor