Overview
This lab session covered insertion sort in depth (its sorted/unsorted-part idea, the shifting mechanism under the hood, and a full code trace) and then moved to merge sort, the divide-and-conquer algorithm with its two functions (the sorting/divide function and the merge function). The recursion trace of merge sort on [4, 3, 2, 10, 12] was started and continued into the second part of the class, including the base case and the merge step. The class closed with a discussion of queues — linear vs. circular queues and priority queues — and their use in operating systems and real systems such as message brokers. It fits in the sorting-algorithms portion of the course, bridging elementary sorting (insertion sort) to divide-and-conquer sorting (merge sort) and introducing queue data structures.
Learning outcomes
- Explain insertion sort in terms of a sorted part and an unsorted part, and why the loop starts at index 1.
- Trace insertion sort's shifting behaviour (not swapping) on a small array, including the intermediate array states.
- Write insertion sort code with
key,j = i - 1, and thewhile j >= 0 and array[j] > keyloop. - State the worst-case and best-case time complexity of insertion sort.
- Describe merge sort as divide and conquer: divide into halves down to single elements, then merge sorted halves.
- Trace the recursive calls of merge sort (midpoint, base case, return behaviour) and the merge step with pointers
i = left,j = mid + 1. - Distinguish a linear queue from a circular queue and explain why the circular queue exists.
- Explain a priority queue and give a real-life example (operating systems).
Core concepts
Insertion sort
Definition: The array is viewed as a sorted part and an unsorted part. The first element is taken as the sorted part; then one element at a time is taken from the unsorted part and inserted into the correct position in the sorted part by comparing with existing elements. Why it matters: It is the baseline comparison-based sorting algorithm and the basis for the complexity discussion (O(n²) worst case, O(n) best case). Connection: It was fully worked through (example + code trace) before merge sort was introduced as a faster-complexity alternative.
Under-the-hood behaviour: shifting, not swapping
Definition: Inside the loop, elements are shifted one position right (array[j + 1] = array[j]) to make room; the key is placed only after the loop ends (array[j + 1] = key).
Why it matters: Exam-style questions ask for the array state mid-iteration; after the first shift the array contains a duplicate of the shifted element, not the key.
Connection: This is why the algorithm is called "insertion" — the key is inserted into its slot after shifting.
Insertion sort implementation
Definition: for i in range(1, n) with key = array[i], j = i - 1, while j >= 0 and array[j] > key, shifting inside, and array[j + 1] = key after.
Why it matters: The and condition matters: if the first condition (j >= 0) is false, the second is not checked.
Connection: The loop starts at 1 because index 0 is the initial sorted part.
Insertion sort cost in terms of inversions
Definition: If exactly k elements are out of place, the cost is Θ(n + I), where I is the number of inversions: each shift removes exactly one inversion and the scan itself is n. Why it matters: I ranges from 0 (already sorted → Θ(n)) to n(n−1)/2 (reverse sorted → Θ(n²)), which is why "always Θ(n)" and "always Θ(n log n)" are both impossible claims for insertion sort. Connection: This is the precise form of the O(n) best case and O(n²) worst case stated above.
Stability of insertion sort
Definition: The shift condition is strictly array[j] > key, not >=. Stopping at an equal element leaves the earlier equal element in front, so insertion sort remains stable with duplicates.
Why it matters: Using >= lets the new element jump ahead of equals, which breaks stability — that is the trap.
Connection: Merge sort is also stable in its standard version; both algorithms are stable.
Merge sort (divide and conquer)
Definition: Two steps: (1) divide — break the array into halves until each part has one element; (2) conquer and merge — merge the smaller sorted arrays into one sorted array (a single element is already sorted). Why it matters: It does not sort by comparing adjacent elements; it divides, sorts smaller parts, and merges them in order. Connection: It has two functions — the merge function and the sorting/divide function — and its recursion trace was the main second-half topic.
Merge sort base case and recursion return
Definition: When left >= right, the function returns (a single element is always sorted). After the first recursive call finishes, execution jumps to the next line (the second recursive call).
Why it matters: Understanding return behaviour is essential to tracing the recursion.
Connection: The trace on [4, 3, 2, 10, 12] depends on this.
The merge step
Definition: Called with left, mid, right; uses i = left, j = mid + 1, and a temporary array, comparing array[i] with array[j] and appending the smaller value.
Why it matters: This is where the actual ordering happens. Merging two sorted arrays of sizes m and n takes O(m + n) worst case.
Connection: Follows the divide phase of the recursion trace.
Merge sort stability and memory
Definition: Merge sort is stable because on a tie the left element is taken, so equal elements preserve their relative order after merging; taking the right element on a tie would reverse the order of equal keys and destroy stability. It requires O(n) auxiliary space for merging. Why it matters: Stability and the extra memory are the standard trade-offs against insertion sort's in-place shifting. Connection: The best case equals the worst case: on already sorted input merge sort is still O(n log n), since it splits and merges everything — the big contrast with insertion sort's O(n) on sorted input, and the reason hybrid sorts (Timsort) use insertion sort on small runs.
Linear queue vs. circular queue
Definition: A linear queue follows FIFO and is static (e.g., made for 10 people / 5 people); after dequeuing, freed space at the front cannot be reused, so an insert may report "full" even though memory exists. A circular queue checks whether it is full and, if not, reuses freed space for the new value. Why it matters: Explains the motivation for the circular queue. Connection: Introduced after merge sort as the queue data-structure topic.
Priority queue
Definition: Elements are inserted/processed according to priority rather than arrival order. Why it matters: Used in operating systems, where jobs arrive with priorities and are executed according to them. Connection: Extended into a student discussion of queues in big data, multithreading/multiprocessing, and Kafka message brokers.
Formulas and maths
for i in range(1, n)— loop over the unsorted part; starts at 1 because the first element is the sorted part.key = array[i]— the current element taken from the unsorted part to be inserted.j = i - 1— index of the last element of the sorted part, where comparison begins.while j >= 0 and array[j] > key— the shifting condition; both conditions must be true, and if the first is false the second is not checked.array[j + 1] = array[j]— shift the larger element one position right.j = j - 1— move the comparison pointer left.array[j + 1] = key— place the key in its correct position after the loop.mid = (left + right) / 2— midpoint of the current subarray; used to split it intoleft..midandmid+1..right.- Recursive calls: sort
left to mid, then sortmid + 1 to right, then merge — the divide-and-conquer order. - Merge pointers:
i = left,j = mid + 1— start of the left half and start of the right half. - Merge loop condition:
while i < midandj < right(as stated in the transcript) — controls the comparison loop over the two halves. - Merge comparison: check
array[i] > array[j]; if false, go to the else branch and append thejvalue, then incrementj— decides which half supplies the next element. - Leftover copying:
for k in range(length of temporary)…array[left + k] = temp[k](as spoken; details [unclear]) — copies the merged temporary array back into the original array. - Insertion sort worst case: O(n²) — used when stating the algorithm's upper bound.
- Insertion sort best case: O(n) — used when stating the algorithm's lower bound.
- Insertion sort cost: Θ(n + I), where I is the number of inversions; I = 0 when sorted (→ Θ(n)) and I = n(n−1)/2 when reverse sorted (→ Θ(n²)).
- Single
forloop is n; aforinside aforis n(n−1), i.e. O(n²) — the student's general rule for reading complexity off loop nesting. - Merge of two sorted arrays of sizes m and n: O(m + n) worst case.
- Merge sort on n elements: O(n log n) in all cases, including already sorted input; recursion depth is log₂ n (e.g., 6 for 64 elements).
- Merge sort on n elements: n/2 rounded down and n/2 rounded up are the two subarray sizes (e.g., 6 and 7 for n = 13); the number of merge operations is n − 1 (e.g., 7 for n = 8).
- Merge sort auxiliary space: O(n).
Worked examples
Insertion sort narrative walkthrough on [4, 3, 2, 9, 5]: - Start: 4 is taken as the sorted part. - 3 comes from the unsorted part, compares with 4; 3 < 4, so 3 is kept first, then 4. - 2 compares with 3 (2 < 3), then with 4 (less), so it goes to the front. - 9 compares with 2, then 3, then 4 — 9 is greater each time, so it is pushed forward and stays at the end. - 5 compares with 2, 3, 4 (greater, pushed forward), then with 9 (9 > 5), so it is placed before 9; 9 stays as it is.
Insertion sort code trace on [4, 3, 2, 10, 12] (n = 5, indices 0–4):
- Iteration i = 1: key = array[1] = 3, j = 0. Condition: j >= 0 true and array[0] = 4 > 3 true → enter loop. array[1] = array[0] → array becomes 4, 4, 2, 10, 12 under the hood (not 3, 4, …). Then j = -1; condition fails (first condition false, second not checked); loop stops. array[j+1] = array[0] = key = 3 → array becomes 3, 4, 2, 10, 12.
- Iteration i = 2: key = array[2] = 2, j = 1. array[1] = 4 > 2 → array[2] = array[1] → 3, 4, 4, 10, 12; j = 0. array[0] = 3 > 2 → array[1] = array[0] → 3, 3, 4, 10, 12; j = -1; loop stops. array[0] = key = 2 → 2, 3, 4, 10, 12. Now the first part is sorted, the rest unsorted.
- Note for competitive-exam style questions: after the first shift the array is 4, 4, 2, 10, 12 — do not write 3, 4, …; the key is placed only after the loop.
Insertion sort outer-loop states on [5, 2, 4, 6, 1, 3]: - Iteration 1 → 2, 5, 4, 6, 1, 3. - Iteration 2 → 2, 4, 5, 6, 1, 3. - Iteration 3 (key = 6) → unchanged, 2, 4, 5, 6, 1, 3 — 6 is already larger than everything in the sorted part.
Merge sort divide example on [4, 3, 2, 10, 12] (indices 0–4):
- First call: left = 0, right = 4, so mid = 2; the left part is 4, 3, 2.
- Divide into left half and right half; keep dividing (4, 3 and 10, 12; then down to single elements).
- Merge back: first merge 3, 4; merge 2, 10; then 12; then merge 3, 4 with 2 (2 comes first), and so on.
Merge sort recursion trace on [4, 3, 2, 10, 12] (indices 0–4):
- Call with left = 0, right = 4: condition 0 >= 4 is false, so no return. mid = (0 + 4) / 2 = 2.
- Left part: 0 to 2 (values 4, 3, 2); right part: 3 to 4 (values 10, 12).
- Call on 0, 2: 0 < 2, so no return; mid = (0 + 2) / 2 = 1. Left part 0, 1; right part 2.
- Call on 0, 1: mid = (0 + 1) / 2 = 0 (integer division, not 0.5). Left part 0, 0; right part 1.
- Call on 0, 0: condition 0 >= 0 is true → return (single element is sorted). Execution returns to the previous call (0, 1), then to the next line: call on mid + 1 to right, i.e. 1, 1.
- Call on 1, 1: 1 >= 1 is true → return. Both halves (4 and 3) are now individually sorted.
- Merge called with left = 0, mid = 0, right = 1: i = 0, j = 0 + 1 = 1; temporary array taken. Check array[i] > array[j], i.e. 4 > 3 → false, so else branch: append the j value (3) and increment j.
- (The transcript's narration of the remaining merge/loop steps becomes garbled here — see Follow-ups.)
Merge sort size and count examples: - n = 8: the number of merge operations is n − 1 = 7. - n = 13: the two subarrays at the first split have sizes 6 and 7 (n/2 floor and ceil). - n = 64: recursion depth is log₂ 64 = 6.
Circular queue example: queue of 5; after dequeuing 1, values 2, 3, 4, 5 remain and the front space is free; a linear queue would refuse an insert ("queue is full"), while a circular queue reuses the space (e.g., inserting 6 there).
Priority queue example: values 3, 1, 2 with arrivals — arrival 101 has priority 3, arrival 102 has priority 1. Processing order: 102 first, then 103, then 101.
Questions asked in class
Q: In-place sorting doubt — the student said insertion sort is in-place sorting, meaning "it will repeat a pattern every time."
A: The instructor explained the sorted-part/unsorted-part view and why the loop starts at 1 and j = i - 1; the student said they understood it as different from what they had in mind.
Q: Are the lab assignment links compulsory, or can they be practiced later? (One showed 6 days, and the student missed the first.) A: All assignments are open; there are no strict timings like a week. All assignments will be closed on the 20th, so submit before that.
Q: Which sorting algorithm is most effective / most prominently used? A: Not given in this part (the instructor moved on to the next student).
Q: Assignment 3, first question shows 0 marks. A: There is some problem/glitch; it shows 0 even to the instructor. Keep it as submitted; marks will be allotted from their side.
Q: Comparison count vs. time complexity (merge vs. insertion) — the student was confused because merge sort seems to do more comparisons while its complexity is better. A: The instructor initially thought the question was about merge sort, then clarified insertion sort had just been completed; the student's question was not resolved in this part.
Q: Can two for loops replace the while?
A: Yes — you can use for i in range(1, length) and an inner for j in range(i, 0, -1) (step −1); it's easy, you don't have to use while.
Q: How to calculate time complexity when there is a while inside a for?
A: For insertion sort we calculate three types; worst case is O(n²), best case is O(n); the student was referred to a video (Abdul Bari) to see the calculation.
Q: Test coverage failing on submission — the insertion sort runs and gives the sorted array but all test cases fail on submit. A: The instructor asked which test cases fail and said they will check it.
Q: At the midpoint where you have 4 and 3, can we instead keep a single element 4 on the left and 3 and 2 on the right — can we divide that way at this division itself? A: The instructor acknowledged the question; noted that the overall algorithm is understandable but one gets lost in the recursive function; said no worries, he will take another (bigger) example in the next class.
Q: In big data / multithreading / multiprocessing, when we process tasks one by one using a queue, is it really scalable for real-time/business use cases? A: Inside the job, libraries (threading, async functions) use these structures — e.g., priority queues — abstracting those layers and exposing only part of it.
Q: Kafka publishes messages to a topic, stored in a message broker which internally uses a queue — is it the same queue we are discussing? A: The instructor could not confirm ("I'm not able to tell you, sorry"); thinks they use the same fundamentals to scale, and that it is all wrappers that parallelize — "possible." The student noted he knew the async/synchronization/threading parts from OS but not the scalable-system side.
Student remark: Understood merge sort overall and the algorithm; implementation via the Python code is fine, but the recursive function is where one gets lost.
Key takeaways
- Insertion sort treats the first element as the sorted part and inserts each subsequent element into its correct position.
- The loop starts at
i = 1(not 0) because index 0 is the initial sorted part;j = i - 1. - The while condition is
j >= 0 and array[j] > key; if the first condition is false, the second is not checked. - Insertion sort shifts elements (
array[j + 1] = array[j]), it does not swap; the key is placed only after the loop. - Mid-iteration, the array contains a duplicate of the shifted element (e.g., 4, 4, 2, 10, 12), not the key.
- Insertion sort worst case is O(n²); best case is O(n); precisely, the cost is Θ(n + I) with I inversions, from 0 (sorted) to n(n−1)/2 (reverse sorted).
- The shift condition is strictly
>(not>=), which keeps insertion sort stable with duplicates; using>=would break stability. - Merge sort is divide and conquer: divide into halves down to single elements, then merge sorted halves; it does not sort by comparing adjacent elements.
- Merge sort has two functions: the merge function and the sorting/divide function.
- Base case of merge sort:
left >= right→ return (a single element is sorted); after the first recursive call returns, execution jumps to the second recursive call. - Merge uses
i = left,j = mid + 1, and a temporary array, appending the smaller ofarray[i]andarray[j]. - Merging sorted arrays of sizes m and n costs O(m + n); merge sort is O(n log n) in all cases (best equals worst), needs O(n) auxiliary space, and is stable because ties take the left element.
- Merge sort on n elements splits into n/2 floor and ceil (6 and 7 for 13), does n − 1 merges (7 for 8), and recurses log₂ n deep (6 for 64).
- A linear queue is static and cannot reuse freed front space; a circular queue reuses it, so it does not falsely report "full."
- A priority queue processes by priority, not arrival order (e.g., in operating systems).
Exam-style questions
Q1. Trace insertion sort on [4, 3, 2, 10, 12] for the first two iterations, showing the array state after each shift. Outline: