Comprehensive Study Notes on Linear Data Structures, Recursion, and Sorting Algorithms

Linear Abstract Data Types: Stacks

  • Fundamental Stack Concepts

    • Definition: A stack is a linear data structure that stores elements in a strict order of insertion and removal governed by the Last-In, First-Out (LIFO\text{LIFO}) principle.

    • Access Restriction: Only one end of the structure—designated as the "top"—is accessible for adding or removing elements. The element placed on top most recently is invariably the first one to be removed.

    • Core Invariant: Elements positioned beneath the top cannot be accessed directly without first removing the preceding elements.

  • Core Stack Operations

    • PUSH

    • Inserts a new element onto the top of the stack.

    • Time complexity: O(1)O(1).

    • POP

    • Removes and returns the element currently residing at the top of the stack.

    • Time complexity: O(1)O(1).

    • PEEK / TOP

    • Reads and returns the top element without removing it from the structure.

    • Time complexity: O(1)O(1).

    • isEMPTY

    • Evaluates whether the stack currently contains zero elements, returning a boolean value.

    • Time complexity: O(1)O(1).

    • isFULL

    • Determines whether the stack has reached its maximum allocated capacity (applicable to fixed-capacity implementations).

    • Time complexity: O(1)O(1).

    • Complexity Rationale: All five operations run in strict constant time (O(1)O(1)) because every operation acts exclusively at the top index/node, requiring zero element shifting or linear searches.

  • Real-World Analogies

    • Plate Dispenser: Spring-loaded cafeteria plate dispensers where the last plate cleaned and stacked on top is the first one lifted off by a customer.

    • Undo Button: Application software pushes every discrete user edit onto an operation history stack; triggering "Undo" pops and reverses the most recent action.

    • Browser Back Button: Visited web pages are pushed sequentially onto a navigation stack; clicking "Back" pops the active page to reveal the immediately preceding URL.

    • Function Call Stack: The runtime architecture pushes active stack frames upon function invocation; upon returning, the current frame is popped off first to resume caller execution.

  • Computational Applications

    • Expression Evaluation: Parsing and evaluating arithmetic expressions in infix, postfix (Reverse Polish Notation), and prefix notations.

    • Syntax & Bracket Matching: Validating matching pairs of parentheses, braces, brackets, and markup tags within compilers, interpreters, and text editors.

    • Backtracking Algorithms: Pathfinding across search spaces, solving mazes, simulating recursion iteratively, and maintaining undo/redo command histories.

    • Memory Management: Managing activation records, tracking local function variables, and maintaining return program counters at runtime.

  • Array-Based Stack Implementation

    • Structural Components:

    • top: An integer variable storing the index of the most recently inserted element (initialized to −1-1 when empty).

    • capacity: The maximum fixed number of elements the array can hold.

    • data[]: The underlying fixed-size contiguous memory array.

    • Structural Advantage: Both insertion and removal act on the exact same boundary index. The array never shifts elements; only the top pointer increments or decrements.

Array-based Stack representation
  • The Push Algorithm:

    1. Check if the stack is full: evaluate whether top==capacity−1\text{top} == \text{capacity} - 1.

    2. If full, raise a Stack Overflow error condition and terminate.

    3. If not full, increment the pointer: top=top+1\text{top} = \text{top} + 1.

    4. Assign the incoming value: data[top]=value\text{data}[\text{top}] = \text{value}.

    • Push Pseudocode:text PUSH(value): if top == capacity - 1: error "Stack Overflow" else: top = top + 1 data[top] = value       

  • Worked Trace: Executing push(42) when top=2\text{top} = 2 on array with prefix [10, 25, 7]:

    • Before: elements at indices 0, 1, 2 are 10, 25, 7; top=2\text{top} = 2.

    • After: top\text{top} moves to 3; index 3 receives 42.

Push operation on an array stack
  • The Pop Algorithm:

    1. Check if the stack is empty: evaluate whether top==−1\text{top} == -1.

    2. If empty, raise a Stack Underflow error condition and terminate.

    3. If not empty, read the element stored at index top\text{top}.

    4. Decrement the pointer: top=top−1\text{top} = \text{top} - 1.

    5. Return the retrieved value.

    • Pop Pseudocode:text POP(): if top == -1: error "Stack Underflow" else: value = data[top] top = top - 1 return value       

  • Worked Trace: Executing pop() when top=3\text{top} = 3 on array containing [10, 25, 7, 42]:

    • Before: top=3\text{top} = 3, pointing to 42.

    • After: value 42 is returned; top\text{top} decrements to 2, pointing to 7.

Pop operation on an array stack
  • Boundary Error Definitions:

    • Stack Overflow: An attempt to insert an element onto a stack that has exhausted its preallocated capacity (top==capacity−1\text{top} == \text{capacity} - 1).

    • Stack Underflow: An attempt to extract or remove an element from an empty stack (top==−1\text{top} == -1).

    • Linked List Stack Implementation

  • Structural Design:

    • Built upon a singly linked list where every discrete node contains data and a reference pointer next.

    • The head of the list functions as the active top.

    • The tail points to NULL.

Singly linked list node structureLinked list stack orientation
  • Push Procedure (Insertion at Head):

    1. Allocate a new node newNode with incoming data.

    2. Direct the pointer: newNode.next=top\text{newNode.next} = \text{top}.

    3. Reposition the head reference: top=newNode\text{top} = \text{newNode}.

    • Push Pseudocode:text function push(data): newNode = Node(data) newNode.next = top top = newNode       

  • Worked Example: Given an existing stack top -> [30] -> [20] -> [10] -> NULL, executing push(40) creates node [40], points [40].next to [30], and sets top to [40]. No other nodes move.

Linked list push operation
  • Pop Procedure (Removal from Head):

    1. Check if top==NULL\text{top} == \text{NULL}; throw a "stack empty" error if true.

    2. Extract value: value=top.data\text{value} = \text{top.data}.

    3. Advance top reference: top=top.next\text{top} = \text{top.next}.

    4. Return the extracted value.

    • Pop Pseudocode:text function pop(): if top == NULL: error "stack empty" value = top.data top = top.next return value       

    • Worked Example: Popping from top -> [40] -> [30] -> [20] -> [10] extracts value 40, moves top to point at [30], and returns 40.

  • Comparative Trade-Offs: Array vs. Linked List Stack

    • Array-Based Stack:

    • Pros: Simple, predictable sequential memory allocation; cache-friendly; rapid access via index pointer arithmetic; zero per-node pointer memory overhead.

    • Cons: Fixed preallocated maximum size; prone to overflow; dynamic resizing requires bulk allocation and copying the entire array (O(n)O(n) realloc).

    • Linked-List-Based Stack:

    • Pros: Dynamically grows and shrinks on demand; unbounded capacity limited only by system heap memory; push/pop never trigger resizing copies.

    • Cons: Additional memory footprint per element to store reference pointers; fragmented heap allocation reduces CPU cache locality; slightly slower pointer traversal overhead.

Linear Abstract Data Types: Queues and Double-Ended Queues (Deques)

  • The Queue Abstract Data Type

    • Definition: A linear sequence of items that operates on the First-In, First-Out (FIFO\text{FIFO}) discipline. The earliest inserted node is the first to be retrieved and removed, identical to a physical line of patrons.

    • Pointer Roles:

    • front: References the node positioned for imminent removal.

    • rear: References the final node in sequence, where incoming elements attach.

FIFO queue representation with front and rear pointers
  • Core Queue Operations:

    • enqueue(x): Allocates and attaches element xx immediately behind rear, subsequently advancing the rear reference. (O(1)O(1))

    • dequeue(): Reads and decouples the element located at front, subsequently moving front forward to front.next. (O(1)O(1))

    • peek(): Returns the data value stored at front without modifying queue contents. (O(1)O(1))

    • isEmpty(): Returns true if front==NULL\text{front} == \text{NULL}, false otherwise. (O(1)O(1))

  • Worked Queue Walkthrough:

    • Initial state: Queue contains [A, B, C] with front at A and rear at C.

    • Operation enqueue(D): Links D after C; rear now points to D. State: [A, B, C, D].

    • Operation dequeue(): Extracts and returns A; front shifts forward to B. State: [B, C, D].

    • The Deque (Double-Ended Queue) Abstract Data Type

  • Definition: A generalized linear data structure allowing element insertion and removal at both extremities (front and rear). Pronounced "deck".

Double-ended queue operations at front and rear
  • Operational Spectrum:

    • addFirst(x): Inserts element xx at the direct front.

    • removeFirst(): Removes and returns the element at the front.

    • addLast(x): Appends element xx at the direct rear.

    • removeLast(): Removes and returns the element at the rear.

  • Behavioral Flexibility:

    • Stack Emulation: Constrain access strictly to addFirst() and removeFirst() (or addLast() and removeLast()) to enforce LIFO\text{LIFO} order.

    • Queue Emulation: Enforce additions through addLast() and removals through removeFirst() to reproduce standard FIFO\text{FIFO} behavior.

    • Full Deque: Utilize all four endpoints concurrently for bi-directional streaming.

  • Worked Deque Walkthrough:

    • Initial state: Deque holds [20, 30, 40].

    • Operation addFirst(10): Prepend 10 to front. State: [10, 20, 30, 40].

    • Operation addLast(50): Append 50 to rear. State: [10, 20, 30, 40, 50].

    • Comparative Breakdown: Queue vs. Deque

  • Insertion Points:

    • Queue: Rear only.

    • Deque: Front and rear.

  • Removal Points:

    • Queue: Front only.

    • Deque: Front and rear.

  • Discipline:

    • Queue: Strict FIFO\text{FIFO}.

    • Deque: FIFO\text{FIFO}, LIFO\text{LIFO}, or hybridized bidirectional.

  • Typical Operations:

    • Queue: enqueue, dequeue.

    • Deque: addFirst, addLast, removeFirst, removeLast.

  • Primary System Uses:

    • Queue: Job buffers, printer spoolers, CPU process scheduling, asynchronous message queues.

    • Deque: Web browser forward/backward histories, sliding-window analytics, work-stealing multithreaded task schedulers.

Recursion and Call Stack Mechanics

  • The Recursive Paradigm

    • Definition: A programming and mathematical method where a function solves a computational problem by invoking smaller instances of itself on reduced inputs until reaching an elementary, directly solvable state.

    • Foundational Structure:

    • Deconstructs complex inputs into self-similar sub-problems.

    • Substitutes state variables through new stack frames rather than mutable loop counters.

    • Everyday Analogies:

    • Facing Mirrors: Standing between two parallel mirrors generates nested reflections of reflections, progressively shrinking until infinitesimal.

    • Russian Nesting Dolls (Matryoshka): Opening an outer wooden doll reveals an identical smaller doll inside, proceeding until encountering the solid, unopenable base doll.

  • The Two Indispensable Pillars of Recursive Functions

    • The Base Case:

    • Evaluates an explicit condition to return an immediate, direct value without executing further recursive invocations.

    • Must be guaranteed reachable under valid input spaces.

    • Serves as the terminating condition that prevents unbounded execution.

    • The Recursive Case:

    • Invokes the function itself on a strictly reduced input argument.

    • Must systematically converge toward the base case threshold.

    • Performs algebraic, logical, or structural composition to merge the sub-result into the parent solution.

  • Case Study: Factorial Computation

    • Code Implementation:c int factorial(int n) { if (n == 0) return 1; // Base Case else return n * factorial(n - 1); // Recursive Case }     

    • Structural Verification:

    • Base Case: n==0n == 0 returns 1 directly.

    • Recursive Case: Computes n×factorial(n−1)n \times \text{factorial}(n - 1), decrementing argument nn by 1.

    • Convergence: For any integer n≥0n \ge 0, consecutive decrements monotonically approach 0.

    • Expansion Trace for factorial(4)\text{factorial}(4):

    • factorial(4)=4×factorial(3)\text{factorial}(4) = 4 \times \text{factorial}(3)

    • factorial(4)=4×(3×factorial(2))\text{factorial}(4) = 4 \times (3 \times \text{factorial}(2))

    • factorial(4)=4×(3×(2×factorial(1)))\text{factorial}(4) = 4 \times (3 \times (2 \times \text{factorial}(1)))

    • factorial(4)=4×(3×(2×(1×factorial(0))))\text{factorial}(4) = 4 \times (3 \times (2 \times (1 \times \text{factorial}(0))))

    • factorial(4)=4×(3×(2×(1×1)))\text{factorial}(4) = 4 \times (3 \times (2 \times (1 \times 1)))

    • factorial(4)=24\text{factorial}(4) = 24

  • Call Stack Lifecycle (Winding and Unwinding)

    • Downward Phase (Call Chain Expansion / Winding):

    • Each progressive invocation pushes an activation record (frame) storing parameters, return points, and local contexts onto the runtime stack:

      1. Pushes factorial(4)

      2. Pushes factorial(3)

      3. Pushes factorial(2)

      4. Pushes factorial(1)

      5. Pushes factorial(0) (Base Case triggered)

    • Upward Phase (Return Resolution / Unwinding):

    • Frames resolve their deferred expressions and pop from the top downward:

      • factorial(0) pops and returns 1.

      • factorial(1) evaluates 1×1=11 \times 1 = 1 and pops.

      • factorial(2) evaluates 2×1=22 \times 1 = 2 and pops.

      • factorial(3) evaluates 3×2=63 \times 2 = 6 and pops.

      • factorial(4) evaluates 4×6=244 \times 6 = 24 and returns the final value.

  • Common Pitfalls in Recursive Design

    • Missing Base Case: Omitting the terminating condition causes endless function self-invocation until hardware/runtime stack memory is exhausted, generating a fatal Stack Overflow.

    • Unreachable Base Case: The recursive reduction fails to converge on the base criterion (e.g., calling n+1n + 1 or miscalculating negative decrements), resulting in infinite recursion.

    • Confusing Call Order with Return Order: Mistaking the top-down traversal sequence for the bottom-up result aggregation sequence.

    • Misinterpreting Sub-Result Combination: Incorrectly combining partial returns (such as adding intermediate factors rather than multiplying them).

Recurrence Relations and Algorithmic Efficiency of Recursion

  • Recurrence Relations

    • Definition: A mathematical equation expressing the total runtime of an algorithm on an input of size nn as a function of its runtime on sub-problems of smaller size.

    • General Archetypes:

    • Linear Recursion: A single self-invocation combined with constant extra overhead per call:       T(n)=T(n−1)+O(1)T(n) = T(n - 1) + O(1)

      • Example: Linear search, simple decrements, iterative factorials.

    • Binary Branching Recursion: Two recursive branches on slightly reduced problem sizes:       T(n)=2T(n−1)+O(1)T(n) = 2T(n - 1) + O(1)

      • Example: Naive calculation of Fibonacci sequences, generate power set.

    • Divide and Conquer: Halving the input size into sub-problems combined with linear partition or merge passes:       T(n)=2T(n/2)+O(n)T(n) = 2T(n / 2) + O(n)

      • Example: Merge Sort.

    • Logarithmic Reduction: Halving the problem size with constant overhead per evaluation:       T(n)=T(n/2)+O(1)T(n) = T(n / 2) + O(1)

      • Example: Binary Search.

  • The Recursion Tree Method

    • Visualizing Tree Expansion for Naive Fibonacci:

    • Recurrence: T(n)=T(n−1)+T(n−2)+O(1)T(n) = T(n - 1) + T(n - 2) + O(1)

    • The execution tree splits into two children for every non-base node:

Naive Fibonacci recursion tree
* **Tree Depth and Call Density:**
  * Tree height equals nn.
  * The number of active invocations roughly doubles at every deeper level: level 0 has 11 call, level 1 has 22, level 2 has 44, up to level kk containing 2k2^k nodes.
  * Total node operations evaluate to approximately 2n2^n, culminating in an exponential running time of O(2n)O(2^n).
  • Efficiency Summary Table of Common Recursive Algorithms

    • Factorial (Linear Recursion):

    • Recurrence: T(n)=T(n−1)+O(1)T(n) = T(n - 1) + O(1)

    • Time Complexity: O(n)O(n)

    • Space Complexity (Stack Depth): O(n)O(n)

    • Naive Fibonacci (Branching Recursion):

    • Recurrence: T(n)=T(n−1)+T(n−2)T(n) = T(n - 1) + T(n - 2)

    • Time Complexity: O(2n)O(2^n)

    • Space Complexity (Maximum Path Depth): O(n)O(n)

    • Binary Search (Divide and Conquer):

    • Recurrence: T(n)=T(n/2)+O(1)T(n) = T(n / 2) + O(1)

    • Time Complexity: O(log⁡(n))O(\log(n))

    • Space Complexity (Call Depth): O(log⁡(n))O(\log(n))

    • Merge Sort (Divide and Conquer):

    • Recurrence: T(n)=2T(n/2)+O(n)T(n) = 2T(n / 2) + O(n)

    • Time Complexity: O(nlog⁡(n))O(n \log(n))

    • Space Complexity (Auxiliary Buffer + Frames): O(n)O(n)

Quadratic Elementary Sorting: Selection Sort and Insertion Sort

  • The Role of Sorting in Computing

    • Fundamental Objectives: Systematic permutation of items into a monotonic sequence (ascending or descending).

    • Computational Utility: Enhances search execution (unlocks binary search at O(log⁡(n))O(\log(n))), eliminates duplicates, identifies bounds, and structures inputs for secondary algorithms.

  • Selection Sort

    • Concept: Partitions array into a sorted left sub-array and an unsorted right sub-array. Sequentially identifies the minimum item across the unsorted sub-array and swaps it directly into the boundary slot.

    • Step-by-Step Procedure:

    1. Initialize outer pointer i=0i = 0, designating ii as the starting min.

    2. Scan unsorted elements from j=i+1j = i + 1 up to n−1n - 1.

    3. If an element a[j]<a[min]\text{a}[j] < \text{a}[\text{min}], reassign min=j\text{min} = j.

    4. After finishing the inner pass, execute a swap between a[i]\text{a}[i] and a[min]\text{a}[\text{min}].

    5. Increment ii to shift the sorted boundary rightward; repeat until sorted.

    • Pseudocode:text for i = 0 to n-2: min = i for j = i+1 to n-1: if a[j] < a[min]: min = j swap(a[i], a[min]) &nbsp;&nbsp;&nbsp;&nbsp;

    • Worked Trace on [29, 10, 14, 37, 13]:

    • Initial State: [29, 10, 14, 37, 13]

    • Pass 1: Global minimum is index 1 (10). Swap with index 0 (29). Result: [10, 29, 14, 37, 13].

    • Pass 2: Unsorted range is [29, 14, 37, 13]. Minimum is 13 (index 4). Swap with index 1 (29). Result: [10, 13, 14, 37, 29].

    • Pass 3: Unsorted range is [14, 37, 29]. Minimum is 14 (index 2). Value already in position; no swap needed. Result: [10, 13, 14, 37, 29].

    • Pass 4: Unsorted range is [37, 29]. Minimum is 29 (index 4). Swap with index 3 (37). Result: [10, 13, 14, 29, 37].

    • Complexity and Characterization:

    • Best Case: O(n2)O(n^2) comparisons.

    • Average Case: O(n2)O(n^2) (computes approximately n2/2n^2 / 2 comparisons on random inputs).

    • Worst Case: O(n2)O(n^2).

    • Space Complexity: O(1)O(1) auxiliary memory (sorts strictly in-place).

    • Maximum Swaps: At most n−1n - 1 write operations.

    • Stability: Not stable (swapping over wide distances can invert the relative order of identical keys).

    • Adaptivity: Non-adaptive; performs identical comparison sequences regardless of initial list order.

  • Insertion Sort

    • Concept: Analogous to arranging playing cards held in a hand. It inspects elements one by one from left to right, inserting each key into its ordered position among previously sorted elements by shifting larger values rightward.

    • Step-by-Step Procedure:

    1. Consider index 0 as inherently sorted.

    2. Iterate index ii from 1 to n−1n - 1, designating key=a[i]\text{key} = \text{a}[i].

    3. Set pointer j=i−1j = i - 1.

    4. While j≥0j \ge 0 and a[j]>key\text{a}[j] > \text{key}, shift elements right: a[j+1]=a[j]\text{a}[j + 1] = \text{a}[j], then decrement jj.

    5. Place the key in the opened space: a[j+1]=key\text{a}[j + 1] = \text{key}.

    6. Advance ii until full array traversal concludes.

    • Pseudocode:text for i = 1 to n-1: key = a[i] j = i - 1 while j >= 0 and a[j] > key: a[j+1] = a[j] j = j - 1 a[j+1] = key &nbsp;&nbsp;&nbsp;&nbsp;

    • Worked Trace on [12, 11, 13, 5, 6]:

    • Initial State: [12, 11, 13, 5, 6]

    • Pass 1 (i=1i = 1, key=11\text{key} = 11): 12>1112 > 11, shift 12 right; insert 11 at index 0. Result: [11, 12, 13, 5, 6].

    • Pass 2 (i=2i = 2, key=13\text{key} = 13): 12<1312 < 13, no shifts required; 13 remains at index 2. Result: [11, 12, 13, 5, 6].

    • Pass 3 (i=3i = 3, key=5\text{key} = 5): Shift 13, 12, and 11 rightward; insert 5 at index 0. Result: [5, 11, 12, 13, 6].

    • Pass 4 (i=4i = 4, key=6\text{key} = 6): Shift 13, 12, and 11 rightward; insert 6 at index 1. Result: [5, 6, 11, 12, 13].

    • Complexity and Characterization:

    • Best Case: O(n)O(n) (array pre-sorted; executes exactly 1 comparison per loop without shifting).

    • Average Case: O(n2)O(n^2) (averages approximately n2/4n^2 / 4 comparisons and shifts).

    • Worst Case: O(n2)O(n^2) (array inverted; requires maximal shift operations).

    • Space Complexity: O(1)O(1) auxiliary memory (in-place).

    • Stability: Stable (equal elements never swap over one another).

    • Adaptivity: Highly adaptive (performance scales linearly on nearly-sorted data; well-suited for streaming online inputs).

  • Comparative Evaluation: Selection Sort vs. Insertion Sort

    • Best-Case Time: Selection Sort is O(n2)O(n^2); Insertion Sort is O(n)O(n).

    • Average-Case Time: Both evaluate to O(n2)O(n^2).

    • Worst-Case Time: Both evaluate to O(n2)O(n^2).

    • Auxiliary Space: Both require O(1)O(1).

    • Stability: Selection Sort is not stable; Insertion Sort is stable.

    • Adaptivity: Selection Sort is non-adaptive; Insertion Sort is adaptive.

    • Dominant Cost Driver: Selection Sort is dominated by comparisons (swaps are capped at n−1n - 1); Insertion Sort is dominated by element shifts/writes.

Diminishing Increments and Bubble Sorting: Bubble Sort and Shell Sort

  • Bubble Sort

    • Mechanism: Repeatedly iterates through the sequence, inspecting adjacent pairs and swapping them if out of order. In each complete sweep, the largest unsorted element "bubbles up" to its terminal index.

    • Algorithmic Steps:

    1. Begin at the start of the list.

    2. Compare adjacent pair a[i]\text{a}[i] and a[i+1]\text{a}[i + 1].

    3. If a[i]>a[i+1]\text{a}[i] > \text{a}[i + 1], swap their positions.

    4. Step to the subsequent pair; iterate to the terminus of the unsorted segment.

    5. Repeat passes until a complete pass occurs with zero swaps recorded.

    • Worked Trace on [5, 1, 4, 2, 8]:

    • Pass 1: Compare (5, 1) -> swap -> [1, 5, 4, 2, 8]; compare (5, 4) -> swap -> [1, 4, 5, 2, 8]; compare (5, 2) -> swap -> [1, 4, 2, 5, 8]; compare (5, 8) -> no swap. Array: [1, 4, 2, 5, 8].

    • Pass 2: Compare (1, 4) -> no swap; compare (4, 2) -> swap -> [1, 2, 4, 5, 8]; compare (4, 5) -> no swap. Array: [1, 2, 4, 5, 8].

    • Pass 3: Zero swaps occur across all comparisons -> early termination triggered. Array confirmed sorted in 3 passes.

    • Complexity Attributes:

    • Best Case: O(n)O(n) (achieved via early-exit flag when array is already sorted).

    • Average Case: O(n2)O(n^2).

    • Worst Case: O(n2)O(n^2) (reverse ordered list).

    • Space Complexity: O(1)O(1) (in-place).

    • Stability: Stable.

  • Shell Sort

    • Mechanism: An optimized generalization of Insertion Sort designed to eliminate inversions across large distances. Rather than comparing strictly adjacent nodes, it compares and swaps items separated by an interval (gap). The gap progressively diminishes to 1, concluding with an efficient insertion sort on an already nearly-sorted array.

    • Gap Sequencing:

    • Common default sequence: Floor divisions halving the span (⌊n/2⌋,⌊n/4⌋,…,1\lfloor n / 2 \rfloor, \lfloor n / 4 \rfloor, \dots, 1).

    • Algorithmic Steps:

    1. Select an initial gap size (typically gap=⌊n/2⌋\text{gap} = \lfloor n / 2 \rfloor).

    2. Compare pairs positioned gap spaces apart.

    3. Execute gapped insertion sort: shift values within interleaved sublists separated by gap.

    4. Reduce gap (gap=⌊gap/2⌋\text{gap} = \lfloor \text{gap} / 2 \rfloor) and repeat passes.

    5. Conclude execution when gap=1\text{gap} = 1.

    • Worked Trace on [9, 8, 3, 7, 5, 6, 4, 1] (n=8n = 8, initial gap=4\text{gap} = 4):

    • Pass with gap=4\text{gap} = 4: Evaluate index pairs separated by 4: (9, 5), (8, 6), (3, 4), (7, 1). Swapping out-of-order pairs produces: [5, 6, 3, 1, 9, 8, 4, 7].

    • Pass with gap=2\text{gap} = 2: Gapped insertion sort across 2 interleaved sublists. Result: [3, 1, 4, 5, 9, 6, 8, 7].

    • Pass with gap=1\text{gap} = 1: Final standard insertion pass; minimal shifts required. Result: [1, 3, 4, 5, 6, 7, 8, 9].

    • Complexity Attributes:

    • Best Case: O(nlog⁡(n))O(n \log(n)) (highly dependent on chosen gap sequences).

    • Average Case: Roughly O(n1.3)O(n^{1.3}) for typical empirical gap series.

    • Worst Case: O(n2)O(n^2) when utilizing basic n/2n / 2 sequences on adversarial inputs.

    • Space Complexity: O(1)O(1) (in-place).

    • Stability: Not stable (long-distance shifts bypass and reorder equivalent keys).

  • Comparative Summary: Bubble Sort vs. Shell Sort

    • Basic Mechanism: Bubble Sort uses adjacent pairwise swaps; Shell Sort uses gapped insertion with a shrinking gap sequence.

    • Average Time Complexity: Bubble Sort is O(n2)O(n^2); Shell Sort is roughly O(n1.3)O(n^{1.3}).

    • Stability: Bubble Sort is stable; Shell Sort is not stable.

    • Best Use Case: Bubble Sort is best for pedagogical instruction and tiny lists; Shell Sort is suited for medium-sized collections requiring simplicity without dynamic memory overhead.

    • Implementation Effort: Bubble Sort is trivial; Shell Sort is simple but requires gap sequence logic.

Advanced Log-Linear Sorting: Merge Sort, Quick Sort, and Heap Sort

  • The Log-Linear Divide-and-Conquer Paradigm

    • Overcomes the asymptotic O(n2)O(n^2) upper bound of basic quadratic routines.

    • General Strategy:

    • Divide: Break dataset into sub-arrays.

    • Conquer: Recursively solve/sort the isolated components.

    • Combine: Stitch partial solutions together into an ordered aggregate.

  • Merge Sort

    • Mechanism: Recursively cleaves the array into halves until single-element lists remain (T(1)T(1) base case). Successive sorted fragments are combined into larger sorted sub-arrays.

    • Step-by-Step Procedure:

    1. Split: Repeatedly halve the array down to single elements.

    2. Sort: A single-element list is inherently sorted (base case).

    3. Merge: Compare front elements from two sorted sub-arrays, placing the smaller element into an auxiliary buffer.

    4. Repeat: Continue merging sorted pairs until one unified sorted array remains.

    • Worked Trace on [38, 27, 43, 3]:

    • Divide step 1: [38, 27] and [43, 3].

    • Divide step 2: [38], [27], [43], [3].

    • Merge pass 1: Interleave [38] and [27] -> [27, 38]. Interleave [43] and [3] -> [3, 43].

    • Merge pass 2: Interleave [27, 38] and [3, 43]. Compare 27 and 3 -> output 3; compare 27 and 43 -> output 27; compare 38 and 43 -> output 38; output 43. Final: [3, 27, 38, 43].

    • Complexity and Characterization:

    • Best Case: O(nlog⁡(n))O(n \log(n)).

    • Average Case: O(nlog⁡(n))O(n \log(n)).

    • Worst Case: O(nlog⁡(n))O(n \log(n)).

    • Space Complexity: O(n)O(n) (requires auxiliary buffers during merging).

    • Stability: Stable.

    • Primary Use: Optimal for linked lists and massive datasets stored in external memory where sequential access dominates.

  • Quick Sort

    • Mechanism: Selects an element as a pivot, partitions the remaining elements such that values smaller than the pivot reside on its left and larger elements on its right, then recursively processes both partitions.

    • Step-by-Step Procedure:

    1. Pick a Pivot: Select a value (e.g., the last element).

    2. Partition: Rearrange elements in-place around the pivot.

    3. Recurse: Apply quicksort to the left and right sub-arrays independently.

    4. Done in Place: Once sub-arrays reach base size (1 or 0 elements), sorting is complete.

    • Worked Trace on [10, 80, 30, 90, 40] (Pivot = 40):

    • Initial state: [10, 80, 30, 90, 40] with pivot 40.

    • Step 1: Scan and segment values smaller than 40 (10, 30) and larger (80, 90). State before final pivot placement: [10, 30, 80, 90, 40].

    • Step 2: Swap pivot into the boundary position between the two segments. State: [10, 30, 40, 90, 80].

    • Result: 40 is permanently fixed at index 2. Independent recursive passes process [10, 30] and [90, 80].

    • Complexity and Characterization:

    • Best Case: O(nlog⁡(n))O(n \log(n)) (balanced partitions).

    • Average Case: O(nlog⁡(n))O(n \log(n)).

    • Worst Case: O(n2)O(n^2) (occurs when sorted/adversarial inputs are paired with poor pivot selection, producing empty and (n−1)(n - 1)-sized partitions).

    • Space Complexity: O(log⁡(n))O(\log(n)) auxiliary space for the recursive call stack.

    • Stability: Not stable.

    • Primary Use: In-memory arrays; preferred in practice due to small constant factors and efficient cache usage.

  • Heap Sort

    • Mechanism: Converts an input array into a binary max-heap. It repeatedly extracts the global maximum from the root, moves it to the array's terminal unsorted boundary, and restores the heap property over the remaining elements.

Binary max-heap structure
  • Step-by-Step Procedure:

    1. Build a Max-Heap: Permute the unsorted array into a max-heap where every parent node is ≥\ge its children.

    2. Extract the Max: Swap the root element (the maximum) with the last element in the active heap.

    3. Shrink & Heapify: Decrement the active heap boundary by one; restore the max-heap invariant via downward sift operations from the root.

    4. Repeat: Continue extracting maximums until the active heap boundary reaches zero.

  • Worked Trace on [4, 10, 3, 5, 1]:

    • Heap construction: Transforms array into max-heap [10, 5, 3, 4, 1].

    • Extraction 1: Swap root 10 with terminal element 1 -> [1, 5, 3, 4, | 10]. Sift down 1 to heapify remaining 4 elements -> [5, 4, 3, 1, | 10].

    • Extraction 2: Swap root 5 with terminal element 1 -> [1, 4, 3, | 5, 10]. Heapify remaining 3 elements -> [4, 1, 3, | 5, 10].

    • Extraction 3: Swap root 4 with terminal element 3 -> [3, 1, | 4, 5, 10]. Heapify -> [3, 1, | 4, 5, 10].

    • Extraction 4: Swap root 3 with 1 -> [1, | 3, 4, 5, 10]. Final array: [1, 3, 4, 5, 10].

  • Complexity and Characterization:

    • Best Case: O(nlog⁡(n))O(n \log(n)).

    • Average Case: O(nlog⁡(n))O(n \log(n)).

    • Worst Case: O(nlog⁡(n))O(n \log(n)) (guaranteed; unaffected by input distribution).

    • Space Complexity: O(1)O(1) auxiliary memory (sorts strictly in-place).

    • Stability: Not stable.

    • Primary Use: Systems requiring guaranteed log-linear runtime without auxiliary memory allocation.

    • Comparison Table: Merge Sort vs. Quick Sort vs. Heap Sort

  • Best / Average Time: Merge Sort: O(nlog⁡(n))O(n \log(n)); Quick Sort: O(nlog⁡(n))O(n \log(n)); Heap Sort: O(nlog⁡(n))O(n \log(n)).

  • Worst Time: Merge Sort: O(nlog⁡(n))O(n \log(n)); Quick Sort: O(n2)O(n^2); Heap Sort: O(nlog⁡(n))O(n \log(n)).

  • Auxiliary Space: Merge Sort: O(n)O(n); Quick Sort: O(log⁡(n))O(\log(n)); Heap Sort: O(1)O(1).

  • Stability: Merge Sort: Stable; Quick Sort: Not stable; Heap Sort: Not stable.

  • In-Place Execution: Merge Sort: No; Quick Sort: Yes; Heap Sort: Yes.

  • Primary Domain: Merge Sort for linked lists and external streams; Quick Sort for general-purpose in-memory processing; Heap Sort for strictly memory-constrained, mission-critical environments.

Non-Comparison Sorting: Radix Sort and Bucket Sort

  • The Non-Comparison Sorting Paradigm

    • Theoretical Threshold: Comparison-based sorting algorithms are mathematically bounded by a lower limit of Ω(nlog⁡(n))\Omega(n \log(n)).

    • Alternative Approach: Non-comparison sorts bypass pairwise comparisons entirely by exploiting structural properties of the input keys (such as digit positions or bounded numerical ranges), enabling linear time performance (O(n)O(n)).

  • Radix Sort

    • Mechanism: Sorts integer values by processing individual digits sequentially, proceeding from the Least Significant Digit (LSD\text{LSD}) up to the Most Significant Digit (MSD\text{MSD}).

    • Subroutine Requirement: Requires an underlying stable sorting subroutine (typically Counting Sort) on each digit pass to preserve the relative order established by earlier passes.

    • Algorithmic Steps:

    1. Identify the maximum element to determine the total number of digits dd.

    2. Iterate through each digit position, moving from the units place leftward to tens, hundreds, etc.

    3. Distribute array values into 10 buckets (indices 0 through 9) based on the active digit.

    4. Collect elements in order from bucket 0 to 9 back into the main array.

    5. Repeat for all dd digits; the array is sorted after the final pass.

    • Worked Trace on [170, 45, 75, 90, 802, 24, 2, 66]:

    • Pass 1 (Units Digit): [170, 90, 802, 2, 24, 45, 75, 66]

    • Pass 2 (Tens Digit): [802, 2, 24, 45, 66, 170, 75, 90]

    • Pass 3 (Hundreds Digit): [2, 24, 45, 66, 75, 90, 170, 802]

    • Complexity Attributes:

    • Time Complexity: O(d⋅(n+k))O(d \cdot (n + k)), where dd is key digit length, nn is list length, and kk is the numeric base (k=10k = 10 for base-10 integers).

    • Space Complexity: O(n+k)O(n + k) (requires auxiliary bucket arrays).

    • Stability: Stable.

    • Best Suited For: Fixed-length keys, machine integers, string tokens, dates, and account identifiers.

  • Bucket Sort

    • Mechanism: Divides the input range into a collection of contiguous intervals called buckets, scatters each value into its corresponding bucket, sorts each bucket individually (often with Insertion Sort), and concatenates the buckets.

    • Data Assumption: Relies on the input data being uniformly distributed across a known continuous interval, such as floating-point values over [0,1)[0, 1).

    • Algorithmic Steps:

    1. Partition the global range into nn equal-width interval buckets.

    2. Scatter each element vv into bucket index ⌊n×v⌋\lfloor n \times v \rfloor.

    3. Sort each non-empty bucket (typically using Insertion Sort).

    4. Concatenate buckets sequentially from lowest to highest.

    • Worked Trace on [0.42, 0.32, 0.23, 0.52, 0.25, 0.47, 0.51]:

    • Bucket [0.2 - 0.4) receives: [0.32, 0.23, 0.25]. Sorted internally -> [0.23, 0.25, 0.32].

    • Bucket [0.4 - 0.6) receives: [0.42, 0.52, 0.47, 0.51]. Sorted internally -> [0.42, 0.47, 0.51, 0.52].

    • Final Concatenation: [0.23, 0.25, 0.32, 0.42, 0.47, 0.51, 0.52].

    • Complexity Attributes:

    • Average Time Complexity: O(n+k)O(n + k) for nn values distributed evenly across kk buckets.

    • Worst-Case Time Complexity: O(n2)O(n^2) (occurs when inputs cluster into a single bucket, collapsing into the worst-case of the secondary sorting routine).

    • Space Complexity: O(n+k)O(n + k).

    • Stability: Dependent on the stability of the inner bucket sorting algorithm.

  • Comparative Evaluation: Radix Sort vs. Bucket Sort

    • Best Input Domain: Radix Sort targets integers and fixed-width strings; Bucket Sort targets uniformly distributed floating-point numbers.

    • Grouping Basis: Radix Sort partitions on discrete digit values at each index; Bucket Sort partitions on numeric interval ranges.

    • Average Time Complexity: Radix Sort is O(d⋅(n+k))O(d \cdot (n + k)); Bucket Sort is O(n+k)O(n + k).

    • Worst-Case Time Complexity: Radix Sort is O(d⋅(n+k))O(d \cdot (n + k)); Bucket Sort is O(n2)O(n^2).

    • Stability: Radix Sort is guaranteed stable; Bucket Sort depends on its inner sorting subroutine.

Comprehensive Algorithmic Comparison: Sorting Taxonomies

  • Global Algorithm Classification Matrix

    • Bubble Sort:

    • Time Complexity: Best O(n)O(n), Average O(n2)O(n^2), Worst O(n2)O(n^2).

    • Space Complexity: O(1)O(1).

    • Properties: Stable, in-place, adaptive (with early exit).

    • Selection Sort:

    • Time Complexity: Best O(n2)O(n^2), Average O(n2)O(n^2), Worst O(n2)O(n^2).

    • Space Complexity: O(1)O(1).

    • Properties: Unstable, in-place, non-adaptive (capped at n−1n - 1 swaps).

    • Insertion Sort:

    • Time Complexity: Best O(n)O(n), Average O(n2)O(n^2), Worst O(n2)O(n^2).

    • Space Complexity: O(1)O(1).

    • Properties: Stable, in-place, adaptive (efficient for nearly-sorted inputs).

    • Shell Sort:

    • Time Complexity: Best O(nlog⁡(n))O(n \log(n)), Average ≈O(n1.3)\approx O(n^{1.3}), Worst O(n2)O(n^2).

    • Space Complexity: O(1)O(1).

    • Properties: Unstable, in-place, non-adaptive.

    • Merge Sort:

    • Time Complexity: Best O(nlog⁡(n))O(n \log(n)), Average O(nlog⁡(n))O(n \log(n)), Worst O(nlog⁡(n))O(n \log(n)).

    • Space Complexity: O(n)O(n).

    • Properties: Stable, out-of-place, non-adaptive.

    • Quick Sort:

    • Time Complexity: Best O(nlog⁡(n))O(n \log(n)), Average O(nlog⁡(n))O(n \log(n)), Worst O(n2)O(n^2).

    • Space Complexity: O(log⁡(n))O(\log(n)).

    • Properties: Unstable, in-place, non-adaptive.

    • Heap Sort:

    • Time Complexity: Best O(nlog⁡(n))O(n \log(n)), Average O(nlog⁡(n))O(n \log(n)), Worst O(nlog⁡(n))O(n \log(n)).

    • Space Complexity: O(1)O(1).

    • Properties: Unstable, in-place, non-adaptive.

    • Radix Sort:

    • Time Complexity: Best/Average/Worst O(d⋅(n+k))O(d \cdot (n + k)).

    • Space Complexity: O(n+k)O(n + k).

    • Properties: Stable, out-of-place, non-comparison.

    • Bucket Sort:

    • Time Complexity: Best/Average O(n+k)O(n + k), Worst O(n2)O(n^2).

    • Space Complexity: O(n+k)O(n + k).

    • Properties: Stability depends on inner sort, out-of-place, non-comparison.

  • Algorithmic Decision Criteria

    • Dataset Size: Tiny collections (n≤10−20n \le 10-20) run efficiently with Insertion Sort due to minimal constant-factor overhead. Massive collections require log-linear (O(nlog⁡(n))O(n \log(n))) or linear (O(n)O(n)) algorithms.

    • Presorted Structure: Highly ordered or nearly-sorted datasets resolve in O(n)O(n) under Insertion Sort or Bubble Sort (with early exit).

    • Memory Limitations: Systems with strict memory limits require in-place algorithms (O(1)O(1) extra space) such as Heap Sort, Shell Sort, or Quick Sort over Merge Sort.

    • Stability Requirements: Applications matching composite records on multiple keys require stable algorithms (Merge Sort, Insertion Sort, Bubble Sort, or Radix Sort).

In-Class Activities, Exercises, and Discussion Questions

  • Activity 1: Hand-Tracing Selection Sort

    • Input Array: [64, 25, 12, 22, 11]

    • Execution Steps:

    • Pass 1: Identify global minimum 11 at index 4. Swap with index 0 (64). Array: [11, 25, 12, 22, 64].

    • Pass 2: Unsorted range is indices 1–4. Minimum is 12 at index 2. Swap with index 1 (25). Array: [11, 12, 25, 22, 64].

    • Pass 3: Unsorted range is indices 2–4. Minimum is 22 at index 3. Swap with index 2 (25). Array: [11, 12, 22, 25, 64].

    • Pass 4: Unsorted range is indices 3–4. Minimum is 25 at index 3. Element already in position; no swap needed. Array: [11, 12, 22, 25, 64].

  • Activity 2: Hand-Tracing Insertion Sort

    • Input Array: [12, 11, 13, 5, 6]

    • Execution Steps:

    • Pass 1 (key=11\text{key} = 11): Compare to 12; shift 12 right; insert 11 at index 0. Array: [11, 12, 13, 5, 6].

    • Pass 2 (key=13\text{key} = 13): Compare to 12; 12<1312 < 13, no shifts; key stays at index 2. Array: [11, 12, 13, 5, 6].

    • Pass 3 (key=5\text{key} = 5): Compare to 13, 12, 11; shift all three right; insert 5 at index 0. Array: [5, 11, 12, 13, 6].

    • Pass 4 (key=6\text{key} = 6): Compare to 13, 12, 11; shift all three right; compare to 5 (5<65 < 6); insert 6 at index 1. Array: [5, 6, 11, 12, 13].

  • Activity 3: Bubble Sort vs. Shell Sort Team Challenge

    • Partner A (Bubble Sort):

    • Array: [12, 4, 9, 1, 7]

    • Pass 1: (12, 4) -> swap -> [4, 12, 9, 1, 7]; (12, 9) -> swap -> [4, 9, 12, 1, 7]; (12, 1) -> swap -> [4, 9, 1, 12, 7]; (12, 7) -> swap -> [4, 9, 1, 7, 12]. (4 comparisons, 4 swaps)

    • Pass 2: (4, 9) -> no swap; (9, 1) -> swap -> [4, 1, 9, 7, 12]; (9, 7) -> swap -> [4, 1, 7, 9, 12]. (3 comparisons, 2 swaps)

    • Pass 3: (4, 1) -> swap -> [1, 4, 7, 9, 12]; (4, 7) -> no swap. (2 comparisons, 1 swap)

    • Pass 4: (1, 4) -> no swap. (1 comparison, 0 swaps -> early exit)

    • Totals: 10 comparisons, 7 swaps.

    • Partner B (Shell Sort):

    • Array: [45, 23, 8, 15, 3, 60, 12] with gap sequence: 3, 1 (n=7n = 7).

    • Gap = 3:

      • Index pairs spaced by 3: (45, 15, 12), (23, 3), (8, 60).

      • Sort (45, 15, 12) -> shifts/swaps produce 12, 15, 45.

      • Sort (23, 3) -> swap -> 3, 23.

      • Sort (8, 60) -> no swap -> 8, 60.

      • Array after gap=3\text{gap} = 3: [12, 3, 8, 15, 23, 60, 45].

    • Gap = 1: Standard insertion pass on nearly-sorted array; shifts values locally into place. Final array: [3, 8, 12, 15, 23, 45, 60].

  • Activity 4: Questions & Discussion Debrief

    • Q1: Which method needed more total comparisons for your array?

    • Response: Bubble Sort requires substantially more total comparisons because every pass inspects all remaining adjacent pairs, whereas Shell Sort's gapped sublists skip comparisons across elements whose order is resolved early.

    • Q2: Which method needed more total swaps?

    • Response: Bubble Sort requires significantly more total swaps. Bubble Sort can only move an element by one adjacent index per swap, whereas Shell Sort moves elements over multi-index gaps in a single operation.

    • Q3: Did Shell Sort's gap rounds move elements closer to their final position faster than Bubble Sort's passes?

    • Response: Yes. Comparing elements across wide gaps allows values located far from their target positions (such as small keys near the end) to travel across multiple indices per step, rapidly reducing the total number of inversions before the final gap=1\text{gap} = 1 pass.

    • Q4: How would each method's effort change if the array had 100 elements instead of 5–7?

    • Response: Bubble Sort's operational cost scales quadratically to approximately 1002/2=5,000100^2 / 2 = 5{,}000 comparisons. Shell Sort's work scales closer to O(n1.3)O(n^{1.3}), performing roughly 1001.3≈400100^{1.3} \approx 400 operations, demonstrating an order-of-magnitude advantage in execution time as nn expands.

    • Q5: Which algorithm would you choose for a nearly-sorted list, and why?

    • Response: Bubble Sort with an early-exit optimization or standard Insertion Sort is preferable. If only a few elements are out of position, both identify the ordered state in O(n)O(n) time on their first pass, avoiding the unnecessary gap passes that Shell Sort executes.

  • Activity 5: Divide-and-Conquer Team Challenge

    • Shared Array: [29, 10, 14, 37, 14, 33, 25, 45] (n=8n = 8)

    • Group A — Merge Sort:

    • Splits into single elements: [29], [10], [14], [37], [14], [33], [25], [45].

    • Merge pairs: [10, 29], [14, 37], [14, 33], [25, 45].

    • Merge quads: [10, 14, 29, 37] and [14, 25, 33, 45].

    • Final merge: [10, 14, 14, 25, 29, 33, 37, 45].

    • Total merge operations: 7 distinct merge events across 3 tree levels.

    • Group B — Quick Sort (Last Element as Pivot):

    • Step 1: Pivot = 45. All other elements are ≤45\le 45. 45 remains at index 7.

    • Step 2: Sub-array [29, 10, 14, 37, 14, 33, 25], Pivot = 25.

    • Partitioning moves values <25< 25 ([10, 14, 14]) to the left of 25, and values >25> 25 ([29, 37, 33]) to the right.

    • Recurse on remaining sub-arrays until all partitions reach size 1.

    • Group C — Heap Sort:

    • Initial heap height: ⌊log⁡2(8)⌋=3\lfloor \log_2(8) \rfloor = 3.

    • Build-heap phase: Rearranges array into a max-heap where root is the global maximum (45).

    • Extraction phase: 7 successive root-swap and sift-down operations order the array in-place.

  • Activity 6: Non-Comparison Sort Hand Exercises

    • Task 1: Radix Sort on [329, 457, 657, 839, 436, 720, 355]:

    • Pass 1 (Units): Buckets sort elements to [720, 355, 436, 457, 657, 329, 839].

    • Pass 2 (Tens): Stable distribution on tens digits yields [720, 329, 436, 839, 355, 457, 657].

    • Pass 3 (Hundreds): Stable distribution on hundreds digits yields [329, 355, 436, 457, 657, 720, 839].

    • Total passes required: 3 (determined by max element 839 having 3 digits).

    • Task 2: Bucket Sort on [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68]:

    • 10 Buckets: [0.0-0.1), [0.1-0.2), [0.2-0.3), [0.3-0.4), [0.4-0.5), [0.5-0.6), [0.6-0.7), [0.7-0.8), [0.8-0.9), [0.9-1.0).

    • Distribution:

      • Bucket 0 ([0.0-0.1)): Empty.

      • Bucket 1 ([0.1-0.2)): 0.17, 0.12 -> sorted: 0.12, 0.17.

      • Bucket 2 ([0.2-0.3)): 0.26, 0.21, 0.23 -> sorted: 0.21, 0.23, 0.26.

      • Bucket 3 ([0.3-0.4)): 0.39 -> sorted: 0.39.

      • Bucket 4 ([0.4-0.5)): Empty.

      • Bucket 5 ([0.5-0.6)): Empty.

      • Bucket 6 ([0.6-0.7)): 0.68 -> sorted: 0.68.

      • Bucket 7 ([0.7-0.8)): 0.78, 0.72 -> sorted: 0.72, 0.78.

      • Bucket 8 ([0.8-0.9)): Empty.

      • Bucket 9 ([0.9-1.0)): 0.94 -> sorted: 0.94.

    • Empty buckets: 0, 4, 5, 8.

    • Final concatenated array: [0.12, 0.17, 0.21, 0.23, 0.26, 0.39, 0.68, 0.72, 0.78, 0.94].