IITP · Semester ISummaries · Quizzes · Assignments

Lecture summary

DAA 27 Sep Lab

27 Sep 20261h 50m2 parts

Source: IITP-big-files\Sem-1\ECS5101-DAA\Lectures\2026-09-27 0000 DAA 27 Sep Lab\summary\notes.md

Overview

This class completed the divide-and-conquer sorting unit: it walked through merge sort's divide and merge steps with a full dry run on an 8-element array, then developed quick sort from the pivot/partition idea through the recursive calls and a code dry run. The session then moved to two new algorithms — maximum subarray sum (Kadane's algorithm, brute force vs. single pass) and binary search — and closed with course logistics (hidden test cases, a lab extension, feedback link). It sits after the introduction of recursion and divide-and-conquer and before the upcoming "cadence" algorithm and further binary search work.

Learning outcomes

  • Trace merge sort on an array: compute mid, split into left/right, apply the base condition, and merge two sorted halves step by step.
  • Explain why merge sort's base condition is length <= 1 while quick sort's is low > high.
  • Implement the partition step of quick sort: choose a pivot, maintain boundary i, swap smaller elements forward, and place the pivot in its final position.
  • Write the recursive quick sort calls using the returned pivot index.
  • Solve maximum subarray sum with Kadane's algorithm and explain why the single pass beats the brute-force double loop.
  • Describe binary search's requirement (sorted array), its three pointers, and its halving logic.
  • Use Python slicing (start:end, step) and tuple swapping without a third variable.

Core concepts

Merge sort (recap)

Divide the array into two halves, recursively sort both halves (left side first, then right side), then merge using a merge function that takes only the left and right parts; leftover values are appended to the result. The base condition is: if the length of the array is <= 1, return the array — it exists because the function recursively calls itself and needs a stopping point. This is the reference divide-and-conquer sort against which quick sort is contrasted.

The merge function

Starts with i = 0, j = 0 and a result array; compares left[i] with right[j]; if left[i] < right[j] it appends the left value and increments i, otherwise it appends the right value and increments j. After the main loop, remaining (already sorted) elements are appended without further comparison. append adds an element to the last position of the array. This is the "combine" half of merge sort.

Merge sort properties

Merge sort is stable: equal elements preserve their relative order after merging, because on a tie the merge must take the left element — taking the right one would reverse the relative order of equal keys and destroy stability. It needs O(n) auxiliary space for merging, which is why quick sort is often preferred for in-memory sorting (less auxiliary memory). The merge step on two sorted arrays of sizes m and n costs O(m + n) in the worst case. On 8 elements there are 7 merge operations (n − 1). An already-sorted input does not help: the complexity stays O(n log n) — it still splits and merges everything, so best case equals worst case (unlike insertion sort, which is O(n) on sorted input — the reason hybrid sorts like Timsort use insertion sort on small runs). Recursion depth for 64 elements is 6 = log₂ 64.

Python slicing

array[start:end] goes from start up to end; with no start/end given it goes from the first element to the last. A step value skips elements — e.g. on 0 1 1 2 3 with step 1 starting from 0, only 0 and 2 are picked (it skips one value each time). Slicing is how the merge sort code produces the left and right halves.

Quick sort

Also divide and conquer, but the major difference is that merge sort divides first and sorts while merging, whereas quick sort places a pivot in its correct position first, then recursively sorts the elements on its left and right. The pivot is "like a center position" — any element chosen as the pivot; it is placed into its correct (final sorted) position. Philosophy: choose the pivot, put everything smaller on the left side and everything bigger on the right side, then quick sort the left side and then the right side.

Partition and the pivot

After the first partition, the pivot is in its final sorted position; everything to its left is smaller and everything to its right is larger, but the two sides are not necessarily sorted yet. Boundary i represents the boundary of elements that are smaller than or equal to the pivot; initially there are no such elements, so i = -1. The partition explanation is marked as "very important."

Quick sort complexity and pivot choice

Average-case complexity is O(n log n) — balanced partitions on average. Worst case is Θ(n²): if the pivot splits the array into parts of size 0 and n−1, the recurrence is T(n) = T(n−1) + Θ(n) = Θ(n²). With the first element as pivot, this happens on both ascending and descending sorted input (every partition is 0 / n−1). Choosing the true median as pivot gives T(n) = 2T(n/2) + n — two halves of size n/2 plus linear partitioning. Median-of-three primarily reduces the likelihood of the worst case. Median-of-medians (deterministic linear-time selection, "BFPRT") guarantees worst-case O(n log n): O(n) pivot selection ⇒ O(n log n) total; randomised quick sort gives O(n log n) only with high probability. Quick sort is unstable — equal elements may swap positions during the long-distance swaps of partitioning.

Quick sort base condition and recursion

Quick sort checks if low > high (unlike merge sort, which checks length ≤ 1), because it checks from both sides; if the indices have crossed/swapped, it returns. low and high are indices only (not arrays) — the call is made with 0 and length of array − 1. After partitioning returns the pivot index, recursively sort the left side with (array, low, pivot index − 1) and the right side with (array, pivot index + 1, high). There are two separate functions: one is the partition, the other is quicksort. Pivot choice is flexible: it can be the first element or any element, not necessarily first or last.

Swapping in Python

Done directly as array[i], array[j] = array[j], array[i] — no third variable needed (unlike C/C++). Used throughout the partition step.

Maximum subarray sum (Kadane's algorithm)

Find the contiguous subarray with the maximum sum. Brute force maintains a result and uses two loops (one over the whole array, one over the internal array), comparing results; time complexity around 9 × 9 = 81 for 9 elements, which is "not cool." Brute force checks n(n+1)/2 subarrays. The single pass maintains a current sum (sum up to now) and a global/maximum sum, updating both in one pass to keep time and space complexity low. With all-negative values the subarray must be non-empty, so the answer is the largest single element; if the empty subarray were allowed the answer would be 0 (Kadane's usually starts at 0).

Divide-and-conquer maximum subarray

The D&C solution considers three candidates at every level: the best subarray wholly in the left half, the best wholly in the right half, and the best crossing the midpoint. The crossing case is solvable in linear time — the key structural fact of the algorithm. Considering only the left-half and right-half bests is wrong; omitting the crossing subarray is the classic wrong solution.

Searching by looking at the middle and eliminating half of the array each time, instead of checking every element (linear search). It only works for a sorted array. Uses three pointers: low, mid, high. Described as "the easier one." It needs O(1) random access, so it cannot be applied to a sorted linked list with the same Θ(log n) run time — indexing into the middle of a linked list costs O(n); you would build a balanced search tree or skip list instead. On duplicates, standard binary search lands on some duplicate; finding the first occurrence needs the "keep searching left" rule (continue searching the left half after a match). Finding an insertion position with binary search is O(log n). In a sorted array of n elements there are n + 1 possible unsuccessful searches.

Formulas and maths

  • mid = length of array // 2 — mid is the split index, // is Python integer division (not plain /); used to divide the array in merge sort.
  • Left part = array[0:mid], right part = array[mid:] — start to mid, and mid to last; used to form the two halves in merge sort.
  • while i < len(left) and j < len(right) — i, j index the left/right halves; with and, if one condition fails the second is not checked and the loop exits; this is the merge loop condition.
  • while i < len(left): result.append(left[i]) (and similarly for the right side) — appends leftover already-sorted elements after the merge loop.
  • quicksort(array, 0, len(array) - 1) — initial call; low = 0, high = last index; used to start quick sort.
  • pivot = array[high] (last element); i = -1; for j in range(low, high) — j runs up to high - 1, excluding the pivot; if array[j] <= pivot: i = i + 1, swap array[i] with array[j]; this is the partition loop.
  • Swap array[i+1] with array[high]; return i + 1 as the pivot index — places the pivot in its final position and reports it.
  • quicksort(array, low, pivot_index - 1) and quicksort(array, pivot_index + 1, high) — recursive calls on the left and right of the pivot.
  • i = low - 1 — partition initialization when the pivot is the high element and no smaller element has been found yet.
  • T(n) = T(n−1) + Θ(n) = Θ(n²) — quick sort worst case when partitions are 0 / n−1 (e.g. first-element pivot on sorted input).
  • T(n) = 2T(n/2) + n — quick sort with the true median as pivot: two halves of size n/2 plus linear partitioning.
  • T(n) = 2T(n/2) + n, T(1) = Θ(1) → Θ(n log n) — merge sort recurrence (Master Theorem case 2, or the recursion tree: n per level × log n levels).
  • current sum = max(array[i], current sum + array[i]) — array[i] is the current element; decides whether to extend the running subarray or restart at the current element; used in Kadane's single pass.
  • max sum = max(max sum, current sum) — keeps the best sum seen so far; used in Kadane's single pass.
  • for i in range(1, length of array) — starts at 1 because the 0th element is taken as the initial value; range goes till length − 1; the Kadane loop.
  • n(n+1)/2 — number of subarrays checked by brute-force maximum subarray.
  • low = 0, high = length of array - 1 — initial binary search bounds.
  • while low < high (as spoken; note the transcript says "while low is less than high") — binary search loop condition.
  • mid = (low + high) / 2 — middle index in binary search.
  • array[mid] == target → return mid (the index); array[mid] < target → low = mid + 1; else → high = mid - 1; if not found → return -1 — the binary search decision branches.
  • Worst-case binary search comparisons = ⌊log₂ n⌋ + 1 — the height of the decision tree; e.g. 127 elements → 6 + 1 = 7; 1,023 elements → 10 (2¹⁰ = 1024 > 1023); 1,024 elements → 10. (Linear search of 1,023 elements would need 31; 8 = log₂ 256.)

Worked examples

Merge sort dry run on [10, 7, 8, 9, 1, 5, 3, 2] (8 elements; the transcript also refers to the array as 1, 2, 3, 6, 7, 8-style values — the concrete values used in the run are the ones below): - Length 8 is not ≤ 1, so no return; mid = 8 // 2 = 4. - Left = indices 0–4 → [10, 7, 8, 9]; right = mid to last → [1, 5, 3, 2]. - Left half: length 4, mid = 4 // 2 = 2 → left [10, 7], right [8, 9]. - [10, 7]: length 2, mid = 2 // 2 = 1 → left [10], right [7]. Each has length 1, so each returns (base condition). - Merge [10] and [7]: i = 0, j = 0; is 10 < 7? False → append right value 7, j = 1. Right side exhausted; leftover loop appends 10. Result [7, 10]. - [8, 9] is divided and merged similarly (transcript: "it will compare and then it will merge", returning 8, 9). - Merge [7, 10] with [8, 9]: - 7 < 8 → append 7, i = 1. - 10 < 8? False → append 8, j = 1. - 10 < 9? False → append 9, j = 2. Right side finished (length 2), loop exits. - Leftover: append 10. Result [7, 8, 9, 10]. - The right half is then sorted the same way.

Quick sort example on [8, 3, 5, 4, 7, 6, 1, 2] with the last element 2 as pivot: - Compare elements with pivot 2: 8 no, 3 no, 5 no, 4 no, 7 no, 6 no, 1 yes → swap the first element (8) with the current smaller element (1): array becomes [1, 3, 5, 4, 7, 6, 8, 2]. - Place pivot: swap array[i+1] (3) with array[high] (2): array becomes [1, 2, 5, 4, 7, 6, 8, 3]. - Pivot 2 is now in its final sorted position; left side smaller, right side larger (sides not necessarily sorted).

Quick sort code dry run on the same array (call quicksort(array, 0, 7)): - low = 0, high = 7, not low > high → call partition with (array, 0, 7). - Pivot = array[7] = 2; i = -1; j runs over range(0, 7) i.e. 0 to 6 (pivot excluded). - 8 < 2? No. … at j = 6, 1 < 2? Yes → i = -1 + 1 = 0; swap array[0] (8) with array[6] (1) → [1, 3, 5, 4, 7, 6, 8, 2]. - Swap array[i+1] = array[1] (3) with array[high] = array[7] (2) → [1, 2, 5, 4, 7, 6, 8, 3]. - Return i + 1 = 1 → pivot index = 1; recursion proceeds on (low, pivot_index - 1) and (pivot_index + 1, high).

Quicksort — right-side recursion and partition dry run: - After the first partition, pivot index = 1. Left call: (array, 0, 1 - 1 = 0) → low = 0, high = 0; 0 is not greater than 0, so it returns (base condition). - Right call: (array, pivot index + 1, high) = (array, 2, 7). - Partition on (2, 7): low = 2, so i = low - 1 = 1; pivot = array[high] = array[7] = 3. - Loop j from 2 to 6 (pivot at index 7 is not checked): - array[2] = 5, 5 < 3 → false - array[3] = 4, 4 < 3 → false - array[4] = 7 → false - array[5] = 6 → false - array[6] = 8 → false - No smaller element found, so the swap inside the loop does not execute. - Place pivot: swap array[i + 1] = array[2] with array[high] = array[7], i.e., 5 swaps with 3 → array becomes 1, 2, 3, 4, 7, 6, 8; return i + 1 = 2. - New pivot index = 2 (pivot element is at that position). Recurse: left call (array, 2, 1) → 2 > 1, so it finishes; then the right side (3, 2, 7) is processed, again finding the pivot (last element), comparing with all elements, swapping smaller elements with the greater one and then into its correct position, and returning its position.

Kadane's dry run (array begins with −2, 1, −3, 4, ...): - Initialize: current sum = -2, max sum = -2. - i = 1: array[1] = 1; current sum = max(1, -2 + 1) = max(1, -1) = 1; max sum = max(-2, 1) = 1. - i = 2: array[2] = -3; current sum = max(-3, 1 + (-3)) = max(-3, -2) = -2; max sum = max(1, -2) = 1. - i = 3: array[3] = 4; current sum = max(4, -2 + 4) = max(4, 2) = 4; max sum = max(1, 4) = 4. - i = 4: array[4] = -1; current sum = max(-1, 4 + (-1)) = max(-1, 3) = 3; max sum = max(4, 3) = 4. - Next step (as computed in class): current sum = max(2, 3 + 2) = max(2, 5) = 5; max sum = max(4, 5) = 5. - i = 6: array[6] = 1; current sum = max(1, 5 + 1) = 6; max sum = max(5, 6) = 6. - Final maximum subarray sum = 6. - Note: the initial value need not be array[0] — any element (e.g., array[7], or −1) can be used.

Kadane's on all-negative input A = [−5, −2, −8, −1, −6]: - Non-empty subarray required, so the answer is the largest single element: −1. - If the empty subarray were allowed the answer would be 0 (Kadane's usually starts at 0).

Kadane's on mixed input A = [−4, 3, −2, 5, −1, 2, −6, 4]: - The subarray [3, −2, 5, −1, 2] sums to 7 — the maximum. - The tempting 5 comes from [3, −2, 5]; the −6 breaks any run reaching the final 4.

Binary search example: - Array: 2, 5, 8, 16, 93, 58, 58 (as spoken); target = 23. - Mid element = 16; 23 > 16, and since the array is sorted, the left half (2, 5, 8, 12, 16) cannot contain 23 → discard it. - Next middle = 38; 23 < 38 → discard that half; element 23 is found.

Binary search comparison counts: - 127 elements: decision tree height ⌊log₂ 127⌋ + 1 = 6 + 1 = 7 comparisons worst case. - 1,023 elements: 10 comparisons (2¹⁰ = 1024 > 1023, so ten halvings suffice); linear search of the same array would need 31. - 1,024 elements: 10 comparisons.

Questions asked in class

  • Vikesh: Doubt on the merge sort base condition — the instructor had said "since 1 is less than or equal to 1 it will return the array," and Vikesh pointed out that 1 ≤ 1 is true. Instructor: "okay, okay, okay… it will get into this and return the array, my bad." (The condition does hold and the array is returned.)
  • Recording doubt: Raised earlier; the instructor confirmed the recording had started.
  • Harun Kumar Agarwal: Asked to see again the part of the code where the pivot index is changed, and why the pivot index variable is maintained after the return. Answer: the partition returns the pivot index (i + 1), which is assigned to the pivot index variable because the left and right sides must be sorted according to it — that is why the pivot index is needed. The student had thought there were two different variables; clarified that there are two different functions (partition and quicksort).
  • Subrat: Could not speak initially (browser problem); later asked about quicksort: his implementation fails some hidden test cases (problem 4, one hidden test case giving a runtime error). Instructor said without seeing the input it is difficult to debug, and that