Courses / Physics I
Computer Science

Searching and sorting ideas

Physics I 195 words Free to read

Searching Data

Finding data efficiently is fundamental in computational physics, from grid tracking to sorting eigenvalues.

Linear search checks every element sequentially. Cost: O(n)O(n).

Binary search repeatedly halves the search space. Cost: O(logn)O(\log n). For 1 billion sorted elements, it takes only about 30 comparisons.

AlgorithmTime CostPrecondition
LinearO(n)O(n)None
BinaryO(logn)O(\log n)Sorted array
Common pitfall: Binary search demands sorted input. On unsorted data, it fails silently and returns wrong answers. Fast algorithms buy speed with preconditions.

Sorting Algorithms

The efficiency of sorting is measured by comparisons relative to input size nn. The lower bound for comparison sorting is Ω(nlogn)\Omega(n \log n).

AlgorithmAverage CostStable?
Bubble sortO(n2)O(n^{2})Yes
Merge sortO(nlogn)O(n\log n)Yes
Quick sortO(nlogn)O(n\log n)No

In practice, use Python's built-in sorted() or np.sort(), which use optimised O(nlogn)O(n\log n) algorithms.

Sorting Algorithm Visualization

Practise this lesson

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

14practice questions
2interactive scenes

Computer Science