Python Tutorial chapters (19)
  1. 01Python Introduction
  2. 02Python Syntax, Keywords & Operators
  3. 03Python Variables & Data Types
  4. 04Python Strings
  5. 05Python Control Statements
  6. 06Python Lists
  7. 07Python Tuples
  8. 08Python Sets
  9. 09Python Dictionaries
  10. 10Python Functions
  11. 11Python Modules
  12. 12Python OOPs
  13. 13Python Exception Handling
  14. 14Python File Handling
  15. 15Python Searching & Sorting
  16. 16Python Advanced Topics
  17. 17Python MySQL
  18. 18Python MongoDB & SQLite
  19. 19Python MCQ

Chapter 15

Python Searching & Sorting

7 topics · 2 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

Searching finds an item in a collection; sorting arranges items in order.

Linear and binary search plus bubble, insertion, selection, merge and quick sort are the standard algorithms taught in every data-structures course and coding interview.

These algorithms train algorithmic thinking and appear in almost every technical interview and exam.

Search boxes, leaderboards, database indexes, scheduling and every place where data must be ordered or looked up quickly.

1

Linear Search in Python

Linear (sequential) search checks each element from the start until the target is found or the list ends. It works on unsorted data. Time complexity: best O(1), average and worst O(n); space O(1).

In short: Look through a pile one item at a time until you find it.

Search: find a target value

Think about it

The simplest search is the baseline for comparing every other algorithm. Finding a name in an unsorted contact list on a small app.

The function usually returns the index of the first match or -1 when missing.

Python already offers x in list and list.

index(x) (raises ValueError if absent), both O(n).

Linear search is the right choice for small or unsorted collections, linked lists, or when you search only once; sorting first costs O(n log n) which is not worth it for a single lookup.

For repeated lookups convert the list to a set or dict (average O(1)).

A sentinel variant appends the target to avoid the bounds check in each iteration.

To find all matches collect indices with a list comprehension.

Key points

  • Sequential search: Another name for linear search.
  • O(n): Time grows proportionally to the number of items.
  • Sentinel: Extra marker element used to simplify the loop.

Example

Code
def linear_search(arr, target):
    for i, value in enumerate(arr):
        if value == target:
            return i                              # first match
    return -1

data = [14, 7, 29, 3, 21, 7]
print(linear_search(data, 29))                    # 2
print(linear_search(data, 99))                    # -1

def find_all(arr, target):
    return [i for i, v in enumerate(arr) if v == target]

print(find_all(data, 7))                          # [1, 5]

people = [{"name": "Ana", "age": 20}, {"name": "Raj", "age": 25}]
match = next((p for p in people if p["name"] == "Raj"), None)
print(match)                                      # {'name': 'Raj', 'age': 25}

print(21 in data, data.index(3))                  # True 3
try:
    data.index(100)
except ValueError:
    print("index() raises ValueError when missing")

lookup = set(data)                                # repeated lookups: O(1) average
print(14 in lookup)                               # True
2

Binary Search in Python

Binary search finds a target in a SORTED sequence by repeatedly comparing it to the middle element and discarding half of the range. Time complexity: O(log n) worst and average, O(1) best; space O(1) iterative, O(log n) recursive.

In short: Guess-the-number game: always guess the middle and ask "higher or lower?".

Think about it

Binary search is the most asked search algorithm in interviews. Dictionary lookup, searching version history, git bisect, database index lookup.

Keep two pointers lo and hi; mid = (lo + hi) // 2 (Python integers do not overflow, unlike fixed-width languages).

If arr[mid] == target return it; if smaller move lo = mid + 1; otherwise hi = mid - 1; loop while lo <= hi.

The data MUST be sorted, otherwise results are wrong.

1,000,000 items need at most about 20 comparisons.

The standard library bisect module provides bisect_left, bisect_right and insort for sorted lists.

Variants: first/last occurrence, lower bound, and binary search on the answer (e.

g.

minimum capacity problems).

Common bugs: infinite loops from lo = mid, or using < instead of <= in the loop condition.

Key points

  • Sorted precondition: Binary search only works on ordered data.
  • O(log n): Work grows with the number of halvings.
  • bisect: Standard-library module for binary search on lists.

Example

Code
def binary_search(arr, target):
    lo, hi = 0, len(arr) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            lo = mid + 1                          # discard left half
        else:
            hi = mid - 1                          # discard right half
    return -1

def binary_search_rec(arr, target, lo=0, hi=None):
    if hi is None:
        hi = len(arr) - 1
    if lo > hi:
        return -1
    mid = (lo + hi) // 2
    if arr[mid] == target:
        return mid
    if arr[mid] < target:
        return binary_search_rec(arr, target, mid + 1, hi)
    return binary_search_rec(arr, target, lo, mid - 1)

data = [3, 8, 15, 23, 42, 56, 78]
print(binary_search(data, 23))                    # 3
print(binary_search(data, 78))                    # 6
print(binary_search(data, 10))                    # -1
print(binary_search_rec(data, 56))                # 5

from bisect import bisect_left, insort
i = bisect_left(data, 42)
print(i, data[i] == 42)                           # 4 True
insort(data, 30)                                  # keeps the list sorted
print(data)                                       # [3, 8, 15, 23, 30, 42, 56, 78]
3

Bubble Sort in Python

Bubble sort repeatedly steps through the list, compares adjacent elements and swaps them if they are out of order; after each pass the largest remaining element "bubbles" to its final position. Time: worst/average O(n^2), best O(n) with an early-exit flag; space O(1); stable and in-place.

In short: Neighbours compare and swap, so big values float to the right like bubbles rise.

Think about it

Simple sorts are the first practical question in lab exams. Educational visualisations; sorting very small arrays on constrained devices.

After pass k the last k elements are final, so the inner loop can shrink: range(n - 1 - i).

Add a swapped flag; if a full pass makes no swap the list is sorted and we stop, giving O(n) on sorted input.

Bubble sort is easy to teach but slow: roughly n(n-1)/2 comparisons.

It is stable (equal elements keep their order).

Use it only for tiny lists or teaching; real code uses sorted() (Timsort, O(n log n)).

Python lets you swap in one line: a[j], a[j + 1] = a[j + 1], a[j].

Key points

  • Pass: One full sweep through the unsorted part.
  • Stable: Equal items keep their relative order.
  • In-place: Uses O(1) extra memory.

Example

Code
def bubble_sort(arr):
    n = len(arr)
    for i in range(n - 1):
        swapped = False
        for j in range(n - 1 - i):                # last i items already placed
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                swapped = True
        if not swapped:                           # no swaps: already sorted
            break
    return arr

nums = [64, 34, 25, 12, 22, 11, 90]
print(bubble_sort(nums))                          # [11, 12, 22, 25, 34, 64, 90]
print(bubble_sort([1, 2, 3, 4]))                  # [1, 2, 3, 4]  (one pass only)
print(bubble_sort([5, 1, 4, 2, 8]))               # [1, 2, 4, 5, 8]

# descending order: change the comparison
def bubble_desc(arr):
    for i in range(len(arr) - 1):
        for j in range(len(arr) - 1 - i):
            if arr[j] < arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr

print(bubble_desc([3, 9, 1, 7]))                  # [9, 7, 3, 1]
4

Insertion Sort in Python

Insertion sort builds a sorted prefix one element at a time: take the next element (key) and shift larger elements of the sorted part one place right until the correct slot is found. Time: worst/average O(n^2), best O(n); space O(1); stable, in-place and adaptive.

In short: Sorting playing cards in your hand: pick up each card and slide it into position.

Sorting: unordered → ordered

Think about it

Frequently asked together with its best-case behaviour. Keeping a small live leaderboard sorted as new scores arrive.

Invariant: before iteration i, arr[0:i] is sorted.

For each i store key = arr[i], set j = i - 1, shift while j >= 0 and arr[j] > key, then place key at arr[j + 1].

It performs fewer writes than bubble sort and is very fast on nearly sorted data, which is why hybrid algorithms (Timsort, introsort) switch to insertion sort for small runs.

Binary insertion sort uses bisect to find the slot but still needs O(n) shifting.

It is an online algorithm: it can sort data as it arrives.

Key points

  • Key: Element currently being inserted.
  • Sorted prefix: Left part that is already ordered.
  • Adaptive: Runs faster when the input is nearly sorted.

Example

Code
def insertion_sort(arr):
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1
        while j >= 0 and arr[j] > key:
            arr[j + 1] = arr[j]                   # shift right
            j -= 1
        arr[j + 1] = key                          # insert at the gap
    return arr

print(insertion_sort([12, 11, 13, 5, 6]))         # [5, 6, 11, 12, 13]
print(insertion_sort([1, 2, 3, 4, 5]))            # sorted input: O(n)
print(insertion_sort(["pear", "apple", "fig"]))   # ['apple', 'fig', 'pear']

# online use: keep list sorted as items arrive
from bisect import insort
scores = []
for s in [50, 20, 80, 35]:
    insort(scores, s)
    print(scores)                                 # [50] [20, 50] [20, 50, 80] [20, 35, 50, 80]
5

Selection Sort in Python

Selection sort divides the list into a sorted and an unsorted part; each pass selects the minimum of the unsorted part and swaps it into the next sorted position. Time: O(n^2) in all cases; space O(1); at most n - 1 swaps; not stable in the usual swap form.

In short: Find the smallest, put it first. Find the next smallest, put it second. Repeat.

Selection sort: pick smallest each round

Think about it

Selection sort is compared with bubble and insertion sort in theory questions on swaps and stability. Choosing top-k items for very small k; teaching algorithm invariants.

Outer loop i from 0 to n - 2; inner loop finds min_index over i..

n-1; swap arr[i] and arr[min_index].

The number of comparisons is always n(n-1)/2 regardless of input order, so there is no best case improvement, but the swap count is minimal, which matters when writes are costly (flash memory).

Instability example: [4a, 4b, 1] -> swapping 1 with 4a moves 4a after 4b.

A stable variant shifts instead of swapping.

Use it only for small lists or teaching.

Key points

  • Minimum selection: Scanning the unsorted part for the smallest value.
  • Swap count: At most n - 1 for selection sort.

Example

Code
def selection_sort(arr):
    n = len(arr)
    for i in range(n - 1):
        min_index = i
        for j in range(i + 1, n):
            if arr[j] < arr[min_index]:
                min_index = j
        if min_index != i:
            arr[i], arr[min_index] = arr[min_index], arr[i]
    return arr

print(selection_sort([64, 25, 12, 22, 11]))       # [11, 12, 22, 25, 64]

# trace of the first pass for [64, 25, 12, 22, 11]
data = [64, 25, 12, 22, 11]
m = min(range(len(data)), key=data.__getitem__)
print("minimum", data[m], "at index", m)          # minimum 11 at index 4
data[0], data[m] = data[m], data[0]
print(data)                                       # [11, 25, 12, 22, 64]

print(selection_sort(["d", "a", "c", "b"]))       # ['a', 'b', 'c', 'd']
6

Merge Sort in Python

Merge sort is a divide-and-conquer algorithm: split the list into halves, recursively sort each half, then merge the two sorted halves. Time: O(n log n) in best, average and worst cases; space O(n); stable.

In short: Split the pile in two, sort each half, then zip the two sorted halves back together.

Merge sort: split → sort → merge

Think about it

Merge sort is the standard example of divide and conquer and guaranteed O(n log n). Sorting huge files that do not fit in memory by merging sorted chunks.

Recurrence T(n) = 2T(n/2) + O(n) gives O(n log n).

The merge step uses two pointers and takes the smaller front element each time; using <= when equal keeps stability.

The recursion depth is log2(n), so Python recursion limits are not a concern.

The auxiliary list makes it not in-place, but it guarantees performance and works well for linked lists and external (disk) sorting.

Python built-in sort (Timsort) is a hybrid of merge sort and insertion sort.

heapq.

merge merges already sorted iterables lazily.

Key points

  • Divide and conquer: Split, solve sub-problems, combine.
  • Merge: Combine two sorted lists into one sorted list.
  • Auxiliary space: Extra memory beyond the input; O(n) here.

Example

Code
def merge(left, right):
    result = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:                   # <= keeps the sort stable
            result.append(left[i]); i += 1
        else:
            result.append(right[j]); j += 1
    result.extend(left[i:])                       # leftovers
    result.extend(right[j:])
    return result

def merge_sort(arr):
    if len(arr) <= 1:
        return arr
    mid = len(arr) // 2
    return merge(merge_sort(arr[:mid]), merge_sort(arr[mid:]))

print(merge_sort([38, 27, 43, 3, 9, 82, 10]))     # [3, 9, 10, 27, 38, 43, 82]
print(merge([1, 4, 9], [2, 3, 10]))               # [1, 2, 3, 4, 9, 10]
print(merge_sort([]), merge_sort([5]))            # [] [5]

import heapq
print(list(heapq.merge([1, 5, 9], [2, 6])))       # [1, 2, 5, 6, 9]
7

Quick Sort in Python

Quick sort picks a pivot, partitions the list so smaller elements come before it and larger after it, then recursively sorts both sides. Time: average O(n log n), worst O(n^2) (bad pivots such as sorted input with a last-element pivot); space O(log n) for the recursion; in-place and not stable.

In short: Choose a pivot; send smaller things left and bigger things right; repeat for each side.

Quick sort: partition around pivot

Think about it

Quick sort partitioning is the most common coding-round sorting question. Implementation core of sort functions in C, C++ and Java primitive arrays.

Lomuto partition: pivot = arr[high]; i = low - 1; scan j from low to high - 1 and swap arr[++i] with arr[j] when arr[j] <= pivot; finally swap pivot into arr[i + 1] and return that index.

Hoare partition uses two converging pointers and does fewer swaps.

Choosing a random or median-of-three pivot makes the worst case very unlikely.

A short Pythonic version builds new lists with comprehensions (clear but uses O(n) extra memory).

Quick sort has excellent cache behaviour, which is why variants (introsort) power many library sorts.

To limit stack depth, recurse into the smaller part and loop on the larger.

Key points

  • Pivot: Element used to split the list.
  • Partition: Rearranging so that smaller values precede the pivot.
  • Lomuto / Hoare: Two classic partition schemes.

Example

Code
import random

def partition(arr, low, high):
    pivot = arr[high]
    i = low - 1
    for j in range(low, high):
        if arr[j] <= pivot:
            i += 1
            arr[i], arr[j] = arr[j], arr[i]
    arr[i + 1], arr[high] = arr[high], arr[i + 1]
    return i + 1

def quick_sort(arr, low=0, high=None):
    if high is None:
        high = len(arr) - 1
    if low < high:
        p = partition(arr, low, high)
        quick_sort(arr, low, p - 1)
        quick_sort(arr, p + 1, high)
    return arr

print(quick_sort([10, 7, 8, 9, 1, 5]))            # [1, 5, 7, 8, 9, 10]
print(quick_sort([3, 3, 1, 2, 3]))                # [1, 2, 3, 3, 3]

def quick_sort_simple(arr):
    if len(arr) <= 1:
        return arr
    pivot = random.choice(arr)                    # random pivot avoids bad cases
    less = [x for x in arr if x < pivot]
    equal = [x for x in arr if x == pivot]
    more = [x for x in arr if x > pivot]
    return quick_sort_simple(less) + equal + quick_sort_simple(more)

print(quick_sort_simple([9, 4, 6, 2, 8, 4]))      # [2, 4, 4, 6, 8, 9]
print(sorted([9, 4, 6, 2]))                       # built-in Timsort for real work

Solved examples

Example 01 · Basic

Perform binary search for 15 in [2, 5, 8, 12, 15, 18, 21]. List the mid values checked.

Given Data:
    Required To Find:

    Index and comparisons

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: lo=0, hi=6, mid=3 -> 12 < 15, lo=4
    Step 2: lo=4, hi=6, mid=5 -> 18 > 15, hi=4
    Step 3: lo=4, hi=4, mid=4 -> 15 found
    Final Answer: Found at index 4 after 3 comparisons (mids 12, 18, 15).

    Approach note: Always move lo to mid+1 or hi to mid-1.

    Example 02 · Intermediate

    Show the array after the first pass of bubble sort on [5, 1, 4, 2, 8].

    Given Data:
      Required To Find:

      Array after pass 1

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: 5>1 swap -> [1,5,4,2,8]
      Step 2: 5>4 swap -> [1,4,5,2,8]
      Step 3: 5>2 swap -> [1,4,2,5,8]
      Step 4: 5<8 no swap
      Final Answer: [1, 4, 2, 5, 8]

      Approach note: The largest element of the pass ends at the right end of the unsorted part.

      Example 03 · Intermediate

      Which sorting algorithm guarantees O(n log n) and is stable among merge, quick and selection sort?

      Given Data:
        Required To Find:

        Algorithm name with reason

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: Selection is O(n^2)
        Step 2: Quick is O(n^2) worst and unstable
        Step 3: Merge is always O(n log n) and stable
        Final Answer: Merge sort.

        Approach note: Remember the trade: merge needs O(n) extra space.

        Example 04 · Basic

        How many comparisons does binary search need in the worst case on a sorted list of 32 elements?

        Given Data:
          Required To Find:

          Comparison count

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: Worst case is about floor(log2 n) + 1 probes
          Step 2: log2(32) = 5
          Step 3: So at most 5 comparisons
          Final Answer: 5 (since log2(32) = 5)

          Approach note: Binary search halves the search space each step: O(log n).

          Real-world applications

          Python

          Using Searching and Sorting in Python in real projects

          Search boxes, leaderboards, database indexes, scheduling and every place where data must be ordered or looked up quickly.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: Binary search works on any list.

          Why this is wrong: It relies on sorted order to discard half the data.

          ✅ Verified Truth: Sort first (or use linear search).

          ⚠️ Exam Tip: State the precondition in answers.

          ❌ Myth: Quick sort is always O(n log n).

          Why this is wrong: Bad pivots lead to O(n^2).

          ✅ Verified Truth: Average is O(n log n); worst is O(n^2).

          ⚠️ Exam Tip: Mention random or median pivot.

          ❌ Myth: Python programmers must write their own sort.

          Why this is wrong: sorted() and list.sort() use optimised Timsort.

          ✅ Verified Truth: Use built-ins in real code.

          ⚠️ Exam Tip: Algorithms are for understanding and interviews.

          Revision notes

          Searching finds an item in a collection; sorting arranges items in order. Linear and binary search plus bubble, insertion, selection, merge and quick sort are the standard algorithms taught in every data-structures course and coding interview.

          High-Yield Quick Revision Points

          1. Linear search O(n); binary search O(log n) but needs sorted data.
          2. Bubble, insertion, selection: O(n^2); insertion best O(n); selection fewest swaps.
          3. Merge sort: O(n log n) always, stable, O(n) space.
          4. Quick sort: average O(n log n), worst O(n^2), in-place, unstable.
          5. In practice use sorted() / list.sort() (Timsort).

          Practice questions

          Question 1 · MCQ (Interview / semester)

          Worst-case time of binary search is

          Question 2 · MCQ (Interview / semester)

          Which sort has best-case O(n) with an early-exit flag?

          Question 3 · MCQ (Interview / semester)

          Merge sort extra space is

          Question 4 · MCQ (Interview / semester)

          Which algorithm performs the fewest swaps (at most n-1)?

          Question 5 · MCQ (Interview / semester)

          Quick sort worst case occurs when

          Question 6 · MCQ (Interview / semester)

          Which module helps with binary search on sorted lists?