Top Banner Ad

ACS201 — Unit 4: Searching and Sorting

Table of Contents (14 sections)

ACS201 · Essentials of Data Structures · Unit 4

Searching and Sorting

Unit Scope & Exam Weightage: This unit covers finding and ordering data: Linear search, binary search, their comparison, Bubble sort and insertion sort, Quick Sort and Selection Sort — trace + C/Python, Merge sort — concept and trace only, and Python built-in sort() and sorted(). The solutions file contains only generic 2026-27 model-paper templates, so all worked questions are labelled predicted and are based on these exact topics and the assignment traces in the syllabus.


Front Page: Importance-Wise Topic Roadmap (Predicted from Syllabus)

Priority Topic (Exact Syllabus) PYQs Asked Marks Weightage Tag
1 Linear search / binary search / comparison 0 real PYQs predicted 7m + 2m Predicted Trace
2 Bubble sort and insertion sort 0 real PYQs predicted 7m Predicted Trace
3 Quick Sort and Selection Sort — trace + C/Python 0 real PYQs predicted 7m Predicted Program
4 Merge sort — concept and trace only 0 real PYQs predicted 5m Predicted Concept
5 Python built-in sort() and sorted() Real connect: Binary search in database index 0 real PYQs predicted 2m + 5m Predicted Theory
6 Python sort() uses Timsort 0 real PYQs predicted 2m Quick Score
7 E-commerce ranking / leaderboard / ML data preprocessing = sorting integrated in #2–#5 — Real Connect
8 Searching and Sorting (unit title/topic) integrated throughout — Unit Frame

2-Hour Last-Night Survival Checklist:

  1. Binary search precondition: the array must be sorted. Compute mid = low + (high-low)//2; if key < a[mid] set high = mid-1, else low = mid+1. Each step halves the range → O(log n).
  2. Bubble trace: compare adjacent pairs repeatedly; after pass 1 the largest reaches the end. On [64,34,25,12], pass 1 gives [34,25,12,64] in 3 swaps.
  3. Insertion trace: grow a sorted prefix. On [5,3,8,1]: [3,5,8,1] → [3,5,8,1] → [1,3,5,8]. Best case O(n) when already sorted.
  4. Complexity table: bubble O(n²), insertion O(n²) (O(n) best), selection O(n²), quick O(n log n) average / O(n²) worst, merge O(n log n) always. Stable: bubble, insertion, merge; not stable: selection, quick.
  5. Python sort: list.sort() sorts in place and returns None; sorted(list) returns a new list. Both use Timsort (merge + insertion hybrid), worst O(n log n).

Searching locates a target element in a collection. Linear search checks elements one by one and works on unsorted data. Binary search repeatedly halves a sorted range by comparing the target with the middle element.

/* linear search */
int linear(int a[], int n, int key) {
    for (int i = 0; i < n; i++) if (a[i] == key) return i;
    return -1;
}

/* binary search */
int binary(int a[], int n, int key) {
    int low = 0, high = n-1, mid;
    while (low <= high) {
        mid = low + (high-low)/2;
        if (a[mid] == key) return mid;
        if (a[mid] < key) low = mid+1;
        else high = mid-1;
    }
    return -1;
}
def linear(a, key):
    for i, x in enumerate(a):
        if x == key: return i
    return -1

def binary(a, key):
    lo, hi = 0, len(a)-1
    while lo <= hi:
        mid = (lo+hi)//2
        if a[mid] == key: return mid
        elif a[mid] < key: lo = mid+1
        else: hi = mid-1
    return -1
Feature Linear search Binary search
Data requirement Any order Must be sorted
Worst case O(n) O(log n)
Best case O(1) (first element) O(1) (middle match)
Extra space O(1) O(1) iterative
Suitable for small/unsorted lists large sorted tables, database indexes

Trace for key 35 in [10,20,30,35,40,50]:

Step low high mid a[mid] Action
1 0 5 2 30 35 > 30 → low = 3
2 3 5 4 40 35 < 40 → high = 3
3 3 3 3 35 found at index 3

Linear search would need four comparisons for the same key; the advantage grows with n.

%%{init: {'theme': 'base', 'look': 'handDrawn', 'themeVariables': {'fontFamily': "'Nunito', sans-serif", 'fontSize': '17px', 'primaryColor': '#EFEAD6', 'primaryBorderColor': '#0F766E', 'lineColor': '#23211C'}}}%%
flowchart TD
    A[low=0, high=n-1] --> B{low <= high?}
    B -->|no| C[Return -1: not found]
    B -->|yes| D[mid = low + (high-low)/2]
    D --> E{a[mid] == key?}
    E -->|yes| F[Return mid]
    E -->|no, key larger| G[low = mid+1]
    E -->|no, key smaller| H[high = mid-1]
    G --> B
    H --> B

Examiner Tip: A 2-mark comparison answer should contain three contrasts: sorted requirement, O(n) vs O(log n), and small vs large datasets. Add “database index uses binary search on a sorted B-tree key list” for the real-connect mark.


2. Bubble Sort and Insertion Sort

Bubble sort repeatedly swaps adjacent elements that are out of order; after each pass the largest unsorted element settles at the end. Insertion sort grows a sorted prefix by taking the next element and shifting larger elements right until the correct slot is found.

/* bubble sort with early stop */
void bubble(int a[], int n) {
    for (int i = 0; i < n-1; i++) {
        int swapped = 0;
        for (int j = 0; j < n-1-i; j++)
            if (a[j] > a[j+1]) {
                int t = a[j]; a[j] = a[j+1]; a[j+1] = t;
                swapped = 1;
            }
        if (!swapped) break;
    }
}

/* insertion sort */
void insertion(int a[], int n) {
    for (int i = 1; i < n; i++) {
        int key = a[i], j = i-1;
        while (j >= 0 && a[j] > key) { a[j+1] = a[j]; j--; }
        a[j+1] = key;
    }
}

Bubble trace on [64,34,25,12]:

Pass Comparisons/swaps Array after pass
1 64↔34, 64↔25, 64↔12 (3 swaps) [34,25,12,64]
2 34↔25, 34↔12 (2 swaps) [25,12,34,64]
3 25↔12 (1 swap) [12,25,34,64]

Total swaps = 6 = n(n-1)/2 for n=4, which is the reverse-sorted worst case.

Insertion trace on [5,3,8,1]:

Step key Action Array
i=1 3 shift 5, insert 3 [3,5,8,1]
i=2 8 no shift (8 > 5) [3,5,8,1]
i=3 1 shift 8,5,3; insert 1 [1,3,5,8]

Insertion sort is O(n²) worst but only O(n) when the input is already sorted; bubble needs a swapped flag to reach O(n) best.


3. Selection Sort, Quick Sort and Merge Sort

Selection sort finds the minimum of the unsorted suffix and swaps it into position i. Quick sort picks a pivot, partitions elements smaller/larger than it, and recurses. Merge sort splits the array into halves, sorts each, and merges the sorted halves.

void selection(int a[], int n) {
    for (int i = 0; i < n-1; i++) {
        int min = i;
        for (int j = i+1; j < n; j++) if (a[j] < a[min]) min = j;
        int t = a[i]; a[i] = a[min]; a[min] = t;
    }
}

Selection trace [64,34,25,12]: i=0 min=3 → [12,34,25,64]; i=1 min=2 → [12,25,34,64]; i=2 no change. Always O(n²) comparisons, at most n-1 swaps.

Quick sort trace [5,3,8,1] with pivot 5: partition smaller [3,1], larger [8]; pivot 3 → smaller [1], larger []; result [1,3,5,8]. Average O(n log n); worst O(n²) when the pivot is consistently the smallest/largest (already sorted input with first-element pivot).

Merge sort trace [64,34,25,12]: split [64,34] and [25,12]; sort to [34,64] and [12,25]; merge by comparing fronts → [12,25,34,64]. Merge sort is O(n log n) in all cases and stable, but needs O(n) extra space.

Algorithm Best Average Worst Stable Extra space
Bubble O(n) O(n²) O(n²) Yes O(1)
Insertion O(n) O(n²) O(n²) Yes O(1)
Selection O(n²) O(n²) O(n²) No O(1)
Quick O(n log n) O(n log n) O(n²) No O(log n) stack
Merge O(n log n) O(n log n) O(n log n) Yes O(n)

Stable sort preserves the relative order of equal keys—important in a leaderboard where students with equal marks should keep their previous ranking order.


4. Python sort() and sorted()

list.sort() sorts the list in place and returns None. sorted(iterable) returns a new sorted list and leaves the original unchanged. Both use Timsort, a hybrid of merge sort and insertion sort, with worst-case O(n log n) and best-case O(n) for already sorted data.

a = [5, 3, 8, 1]
b = sorted(a)        # [1,3,5,8]; a unchanged
a.sort()             # a becomes [1,3,5,8]; returns None
a.sort(reverse=True) # [8,5,3,1]
marks = [("Asha",88), ("Ravi",91)]
marks.sort(key=lambda x: x[1])   # sort by marks
Feature sort() sorted()
Modifies original Yes No
Return value None New list
Works on any iterable No (list only) Yes (tuple, dict keys, etc.)
Algorithm Timsort Timsort

Real connect: a database index stores keys in sorted order so binary search can locate a record in O(log n); e-commerce ranking and leaderboards sort by score; ML preprocessing sorts features before discretisation or quantile binning.


5. Predicted Exam-Ready Questions (Solved — Not Verbatim PYQs)

Q (predicted from “Linear search / binary search / comparison”): Compare linear and binary search and trace binary search for key 35 in [10,20,30,35,40,50].

Solution: Comparison from Section 1 table. Trace from Section 1 table: step 1 mid=2 (30 → low=3), step 2 mid=4 (40 → high=3), step 3 mid=3 (35 found at index 3). Binary search needs 3 comparisons; linear search needs 4. Binary search requires sorted data; linear search does not.


Predicted Q2 (7 Marks | Bubble Sort Trace)

Q (predicted from assignment “Bubble sort trace on [64,34,25,12]” and “count swaps”): Sort [64,34,25,12] using bubble sort and count the swaps.

Solution: Pass 1: 64↔34, 64↔25, 64↔12 → [34,25,12,64] (3 swaps). Pass 2: 34↔25, 34↔12 → [25,12,34,64] (2 swaps). Pass 3: 25↔12 → [12,25,34,64] (1 swap). Total 3+2+1 = 6 swaps, which is n(n-1)/2 for n=4.


Predicted Q3 (7 Marks | Insertion Sort Trace)

Q (predicted from assignment “Insertion sort trace on [5,3,8,1]”): Trace insertion sort on [5,3,8,1] and write the C loop used.

Solution: Trace from Section 2: [3,5,8,1] → [3,5,8,1] → [1,3,5,8]. The loop:

for (int i=1; i<n; i++) {
    int key = a[i], j = i-1;
    while (j >= 0 && a[j] > key) { a[j+1] = a[j]; j--; }
    a[j+1] = key;
}

Best case O(n) when already sorted; worst O(n²) when reverse sorted.


Predicted Q4 (7 Marks | Selection Sort Program)

Q (predicted from “Quick Sort and Selection Sort — trace + C/Python”): Write a C program for selection sort and trace it on [64,34,25,12].

Solution: Code from Section 3. Trace: after i=0 → [12,34,25,64]; after i=1 → [12,25,34,64]; after i=2 unchanged. Selection sort performs O(n²) comparisons but at most n−1 swaps, and it is not stable.


Predicted Q5 (5 Marks | Merge Sort Concept and Trace)

Q (predicted from “Merge sort — concept and trace only”): Explain merge sort and trace it on [64,34,25,12].

Solution: Split into [64,34] and [25,12]; recursively sort to [34,64] and [12,25]; merge by repeatedly taking the smaller front element: compare 34 vs 12 → 12, 34 vs 25 → 25, then 34, then 64. Result [12,25,34,64]. Complexity O(n log n) always, stable, O(n) extra memory.


Predicted Q6 (2 Marks | Python Built-ins)

Q (predicted from “Python built-in sort() and sorted()” and “Python sort() uses Timsort”): Differentiate sort() from sorted() and name the algorithm Python uses.

Solution: sort() mutates the list in place and returns None; sorted() returns a new sorted list and leaves the original unchanged. Python uses Timsort (merge + insertion hybrid), worst case O(n log n), best case O(n) on sorted input.


Predicted Q7 (7 Marks | Sorting in an Application)

Q (predicted from “E-commerce ranking / leaderboard / ML data preprocessing = sorting”): A leaderboard stores (name, marks). Explain which sort is suitable when equal marks must keep their earlier order, and write Python code.

Solution: Use a stable sort—merge sort, insertion sort, or Python's Timsort. Unstable selection/quick sort may reorder equal keys.

board = [("Asha",91), ("Ravi",88), ("Neha",91), ("Karan",75)]
board.sort(key=lambda x: x[1], reverse=True)
# [('Asha',91), ('Neha',91), ('Ravi',88), ('Karan',75)]

Asha and Neha both have 91 and remain in their original relative order because Timsort is stable.


6. Practice Questions (Self-Test)

  1. (2 Marks) Why must an array be sorted before binary search? (Ans: the discard-half decision relies on ordering.)
  2. (7 Marks) Write both searches in Python and count comparisons for key 40 in [10,20,30,40,50].
  3. (7 Marks) Bubble sort [5,1,4,2,8] and show each pass with the number of swaps.
  4. (7 Marks) Quick sort [7,2,9,4,1] using the first element as pivot; show the partition at each level.
  5. (2 Marks) What is Timsort and what is its worst-case complexity? (Ans: hybrid merge/insertion sort, O(n log n).)