Courses / Mathematics I
Programming Elements

Searching and Sorting

Mathematics I 241 words Free to read

Searching Strategies

Searching (finding an item) and sorting (ordering items) are fundamental algorithmic tasks that make complexity theory practical.

Linear search scans every element one by one, taking O(n)O(n) time. It works on any list, whether sorted or not.

Binary search repeatedly halves a sorted list by comparing the target to the middle, taking O(logn)O(\log n) time.

AlgorithmTime ComplexityPrecondition
Linear SearchO(n)O(n)None (Any list)
Binary SearchO(logn)O(\log n)Must be sorted

Common Pitfall: Applying binary search to an unsorted list yields wrong answers. It discards half the data assuming order, so it skips the target. Sort first or use linear search.

Halving only works if the order is real -- shown by breaking it

Sorting and Trade-offs

Sorting arranges elements into order. Simple methods like bubble sort, selection sort, and insertion sort run in O(n2)O(n^2) time — fine for small data, but slow at scale.

Efficient methods like merge sort and quicksort run in O(nlogn)O(n \log n) time, the limit for comparison-based sorting. They use divide and conquer: split data, sort recursively, and combine.

Sort TypeAlgorithmsSpeed
SimpleBubble, Selection, InsertionO(n2)O(n^2) (Slow)
EfficientMerge, QuicksortO(nlogn)O(n \log n) (Fast)

Sorting once lets you binary-search repeatedly. Choosing an algorithm depends on data size and how often you run the task.

Practise this lesson

The explanation above is free to read. The graded practice for this lesson lives in the Tryals app.

13practice questions
2interactive scenes

Programming Elements