Comprehensive Study Guide to Searching and Sorting Algorithms

Introduction to Searching

  • Core Definition: Searching is the computational process of determining whether a specific target value exists within an array or data structure.
  • Search Outcomes:
    • Successful Search: The target value is present in the array; the algorithm terminates successfully and outputs the exact index or position of the element.
    • Unsuccessful Search: The target value does not exist within the array; the algorithm terminates with a failure indicator or message.
  • Primary Searching Techniques:
    • Linear Search: Used primarily when the data elements are unordered or unsorted.
    • Binary Search: Used exclusively when data elements are organized in a sorted sequence (typically ascending order); exhibits significantly higher execution efficiency.
  • Algorithmic Selection Criterion: The choice between linear and binary search is dictated entirely by how the underlying array elements are structured and arranged.

Linear Search (Sequential Search)

  • Alternate Nomenclature: Also formally designated as sequential search.
  • Operational Definition: A fundamental searching algorithm that sequentially traverses an array, evaluating each element one by one starting from the first position until either the target element is identified or the end of the collection is reached.
  • Primary Domain: Most effective and standard for unsorted arrays where no ordering properties can be exploited.
  • Step-by-Step Algorithmic Procedure:
    • Step 1: Initialize the search at the first index of the array (index 0\text{index } 0).
    • Step 2: Compare the value of the current array element with the search key (VAL\text{VAL} or key\text{key}).
    • Step 3: If the current element matches the search key, conclude the search as successful and return the current position/index.
    • Step 4: If the current element does not match the search key, increment the index pointer and transition to the next adjacent element.
    • Step 5: If the traversal reaches the terminal boundary of the array without encountering a match, conclude the search as unsuccessful (the element is not present).
  • Complexity Analysis:
    • Best-Case Time Complexity: O(1)O(1) — Occurs when the target key is located at the first position of the array (index 0\text{index } 0), requiring exactly one comparison.
    • Average-Case Time Complexity: O(n)O(n) — On average across arbitrary distributions, the algorithm inspects approximately half of the total elements (n2\frac{n}{2} comparisons).
    • Worst-Case Time Complexity: O(n)O(n) — Occurs when the target key is situated at the terminal position (index n−1\text{index } n - 1) or is completely absent from the array, necessitating a full traversal of all nn elements.
    • Space Complexity: O(1)O(1) — Operates as an in-place search requiring strictly constant extra auxiliary space for a minimal set of scalar tracking variables (such as the loop index counter and search key), irrespective of the size of the array (nn).

Linear search comparison traversal finding element 20

  • Demonstrative Walkthroughs:
    • Introductory Example (n=10n = 10):
    • Array: {10,8,2,7,3,4,9,1,6,5}\left\{ 10, 8, 2, 7, 3, 4, 9, 1, 6, 5 \right\}
    • Target: VAL=7\text{VAL} = 7
    • Traversal: Index 0 (10)→Index 1 (8)→Index 2 (2)→Index 3 (7)\text{Index } 0 \ (10) \rightarrow \text{Index } 1 \ (8) \rightarrow \text{Index } 2 \ (2) \rightarrow \text{Index } 3 \ (7)
    • Result: Element found at position 33 (using zero-based indexing).
    • Trace Example 1 (n=5n = 5):
    • Array: [10,25,30,45,50][10, 25, 30, 45, 50]
    • Target: VAL=45\text{VAL} = 45
    • Sequential Comparisons:
      • 10≠4510 \neq 45
  • 25≠4525 \neq 45
  • 30≠4530 \neq 45
    • 45=4545 = 45
    • Result: Element successfully identified at index 33 (the 4th position).
  • Trace Example 2 (n=9n = 9):
    • Array: [29,87,89,21,23,17,11,10,14][29, 87, 89, 21, 23, 17, 11, 10, 14]
    • Target Key: K=17K = 17
    • Sequential Comparisons:
    • Index 0:29≠17\text{Index } 0: 29 \neq 17
  • Index 1:87≠17\text{Index } 1: 87 \neq 17
  • Index 2:89≠17\text{Index } 2: 89 \neq 17
  • Index 3:21≠17\text{Index } 3: 21 \neq 17
  • Index 4:23≠17\text{Index } 4: 23 \neq 17
    • Index 5:17=17\text{Index } 5: 17 = 17
    • Result: Search halts; key is located at index 55.
  • Trace Example 3 (n=9n = 9):
    • Array: [10,50,30,70,80,60,20,90,40][10, 50, 30, 70, 80, 60, 20, 90, 40]
    • Target Key: VAL=20\text{VAL} = 20
    • Traversal Path: Iterates sequentially through indices 0,1,2,3,4,50, 1, 2, 3, 4, 5 until encountering 2020 at index 66.
  • Trace Example 4 (n=8n = 8):
    • Array: [65,20,10,55,32,12,50,99][65, 20, 10, 55, 32, 12, 50, 99]
    • Search Element: 1212
    • Execution Steps:
    • Step 1: Compare search element (1212) with first element (6565). No match (65≠1265 \neq 12); increment pointer.
  • Step 2: Compare with second element (2020). No match (20≠1220 \neq 12); increment pointer.
  • Step 3: Compare with third element (1010). No match (10≠1210 \neq 12); increment pointer.
  • Step 4: Compare with fourth element (5555). No match (55≠1255 \neq 12); increment pointer.
  • Step 5: Compare with fifth element (3232). No match (32≠1232 \neq 12); increment pointer.
  • Step 6: Compare with sixth element (1212). Match confirmed (12=1212 = 12); terminate comparisons and display that the element is found at index 55.

Binary Search

  • Core Concept & Prerequisites:
    • Operates strictly and exclusively on sorted collections (e.g., arrays sorted in ascending numerical order).
    • Relies on repeated bisection (halving) of the active search range until the target element is isolated.
  • Real-World Analogy: Conceptually identical to searching for an entry in a physical dictionary or telephone directory: the user opens the book near the absolute middle, observes the entry, and discards either the entire preceding or succeeding half based on alphabetical ordering.
  • Mathematical Formulation & Pointer Variables:
    • Low Boundary: BEG\text{BEG} (or Low\text{Low}, initialized to 00).
    • High Boundary: END\text{END} (or High\text{High}, initialized to n−1n - 1).
    • Midpoint Index Formula:     MID=⌊BEG+END2⌋\text{MID} = \left\lfloor \frac{\text{BEG} + \text{END}}{2} \right\rfloor
  • Algorithmic Mechanics:
    • Step 1: Compute the middle index MID\text{MID}.
    • Step 2: Compare the search target (VAL\text{VAL} or key\text{key}) with the element at the midpoint (A[MID]A[\text{MID}]):
    • Condition A (Match): If VAL=A[MID]\text{VAL} = A[\text{MID}], the search is successful; return POS=MID\text{POS} = \text{MID}.
    • Condition B (Target is Smaller): If VAL<A[MID]\text{VAL} < A[\text{MID}], the search space is restricted to the lower/left sub-array; set END=MID−1\text{END} = \text{MID} - 1.
    • Condition C (Target is Larger): If VAL>A[MID]\text{VAL} > A[\text{MID}], the search space is restricted to the upper/right sub-array; set BEG=MID+1\text{BEG} = \text{MID} + 1.
    • Step 3: Re-evaluate and repeat while BEG≤END\text{BEG} \le \text{END}.
    • Step 4 (Termination): If BEG>END\text{BEG} > \text{END}, the search boundary has collapsed, signifying that the key does not exist within the array.
  • Complexity Analysis:
    • Search Space Reduction: Each iterative comparison divides the active search space strictly in half (n2k\frac{n}{2^k} after kk iterations).
    • Best-Case Time Complexity: O(1)O(1) — Occurs when the middle element inspected during the very first comparison corresponds directly to the target key.
    • Average-Case Time Complexity: O(log⁡(n))O(\log(n)) (specifically O(log⁡2(n))O(\log_2(n))) — Search intervals are recursively halved at each processing step.
    • Worst-Case Time Complexity: O(log⁡(n))O(\log(n)) — Occurs when the key is situated at the outermost leaf of the search tree or is not present, requiring the maximum number of logarithmic divisions (⌊log⁡2(n)⌋+1\lfloor \log_2(n) \rfloor + 1).
    • Space Complexity: O(1)O(1) — Requires strictly constant extra memory for managing index tracking variables (left/BEG\text{left}/\text{BEG}, right/END\text{right}/\text{END}, and mid/MID\text{mid}/\text{MID}).

Binary search division steps locating key 7 in a 10-element array

  • Detailed Execution Examples:
    • Example 1 (n=11n = 11):
    • Array: {0,1,2,3,4,5,6,7,8,9,10}\left\{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 \right\}
    • Target: VAL=9\text{VAL} = 9
    • Iteration 1: BEG=0\text{BEG} = 0, END=10\text{END} = 10. Midpoint calculation:       MID=⌊0+102⌋=5\text{MID} = \left\lfloor \frac{0 + 10}{2} \right\rfloor = 5       Array value: A[5]=5A[5] = 5. Compare: 5<95 < 9. Target lies in right half; update BEG=MID+1=6\text{BEG} = \text{MID} + 1 = 6.
    • Iteration 2: BEG=6\text{BEG} = 6, END=10\text{END} = 10. Midpoint calculation:       MID=⌊6+102⌋=8\text{MID} = \left\lfloor \frac{6 + 10}{2} \right\rfloor = 8       Array value: A[8]=8A[8] = 8. Compare: 8<98 < 9. Target lies in right half; update BEG=MID+1=9\text{BEG} = \text{MID} + 1 = 9.
    • Iteration 3: BEG=9\text{BEG} = 9, END=10\text{END} = 10. Midpoint calculation:       MID=⌊9+102⌋=9\text{MID} = \left\lfloor \frac{9 + 10}{2} \right\rfloor = 9       Array value: A[9]=9A[9] = 9. Compare: 9=99 = 9. Match found; return index position POS=9\text{POS} = 9.
    • Example 2 (n=10n = 10):
    • Array: [1,2,3,4,5,6,7,8,9,10][1, 2, 3, 4, 5, 6, 7, 8, 9, 10] (indices 00 through 99)
    • Target Key: 77
    • Step 1: Low=0\text{Low} = 0, High=9\text{High} = 9, Mid=4\text{Mid} = 4 (A[4]=5A[4] = 5). Since 7>57 > 5, eliminate the left half and consider the right sub-array.
    • Step 2: Low=5\text{Low} = 5, High=9\text{High} = 9, Mid=7\text{Mid} = 7 (A[7]=8A[7] = 8). Since 7<87 < 8, eliminate the right half and consider the left sub-array.
    • Step 3: Low=5\text{Low} = 5, High=6\text{High} = 6, Mid=5\text{Mid} = 5 (A[5]=6A[5] = 6). Since 7>67 > 6, consider the right half.
    • Step 4: Pointer convergence: Low=Mid=High=6\text{Low} = \text{Mid} = \text{High} = 6 (A[6]=7A[6] = 7). Target is present at index 66.
    • Example 3 (n=10n = 10):
    • Array: [2,5,8,12,16,23,38,56,72,91][2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
    • Target Key: 2323
    • Step 1: Set L=0L = 0, H=9H = 9, M=4M = 4 (A[4]=16A[4] = 16). Because 23>1623 > 16, proceed to the 2nd half.
    • Step 2: Set L=5L = 5, H=9H = 9, M=7M = 7 (A[7]=56A[7] = 56). Because 23<5623 < 56, proceed to the 1st half of the remaining segment.
    • Step 3: Set L=5L = 5, H=6H = 6, M=5M = 5 (A[5]=23A[5] = 23). Target matched (23=2323 = 23); terminate and return index 55.
    • Example 4 (n=9n = 9):
    • Array: [10,12,20,32,50,55,65,80,99][10, 12, 20, 32, 50, 55, 65, 80, 99]
    • Case A: Search for element 1212:
      • Step 1: Compare search element (1212) with middle element at index 44 (5050). Since 12≠5012 \neq 50 and 12<5012 < 50, restrict search space to left sublist: {10,12,20,32}\left\{ 10, 12, 20, 32 \right\}.
    • Step 2: Compute midpoint of left sublist; middle element at index 11 is 1212. Since 12=1212 = 12, search succeeds with message: "Element found at index 1".
  • Case B: Search for element 8080:
    • Step 1: Compare search element (8080) with middle element at index 44 (5050). Since 80≠5080 \neq 50 and 80>5080 > 50, restrict search space to right sublist: {55,65,80,99}\left\{ 55, 65, 80, 99 \right\}.
  • Step 2: Compare search element (8080) with middle element of sublist at index 66 (6565). Since 80≠6580 \neq 65 and 80>6580 > 65, restrict search space to remaining right sublist: {80,99}\left\{ 80, 99 \right\}.
  • Step 3: Compare search element (8080) with middle element at index 77 (8080). Match confirmed; search succeeds with message: "Element found at index 7".

Introduction to Sorting

  • Core Definition: Sorting represents the systemic programmatic arrangement of data elements within an array or linear collection into a designated structured order, specifically ascending (non-decreasing) or descending (non-increasing) order.
  • Structural Transformation Illustration:
    • Unsorted State: int A[] = {21, 34, 11, 9, 1, 0, 22};
    • Ascending Sorted State: A[] = {0, 1, 9, 11, 21, 22, 34};
  • Algorithmic Importance:
    • Arranges arbitrary records into strict numerical, lexicographical, or custom ordinal systems.
    • Optimizes the computational performance of dependent downstream procedures, most notably enabling logarithmic binary searching and efficient multi-list merging.
  • Taxonomy of Sorting Techniques:
    • Internal Sorting: Pertains to algorithms handling datasets that reside entirely within the computer's primary high-speed random-access memory (RAM).
    • External Sorting: Pertains to algorithms specialized for ordering large volumes of data that exceed primary memory capacity, requiring secondary/auxiliary storage devices (such as magnetic disks or solid-state drives).

Bubble Sort

  • Core Principle: An elementary comparison-based sorting method that iterates through an array from lowest to highest index, iteratively shifting and "bubbling" the largest unsorted element toward its proper terminal index position during each successive pass.
  • Algorithmic Invariant: Following the completion of Pass kk, the kk-th largest elements are guaranteed to occupy their permanent, sorted positions at the tail end of the array.
  • Operational Steps:
    • Step 1: Commence scanning at the initial element of the array (index 0\text{index } 0).
    • Step 2: Compare the value of the active element with its immediate successor element.
    • Step 3: If the left element exceeds the right element in magnitude (A[j]>A[j+1]A[j] > A[j+1]), swap their positions.
    • Step 4: Advance one position to the right and repeat the comparison and conditional swap for the subsequent adjacent pair.
    • Step 5: Continue until reaching the boundary of the unsorted segment; the maximum value of the sub-array has settled into the final position.
    • Step 6: Decrement the active traversal boundary and repeat the procedure until zero swaps occur or all elements have been processed.
  • Complexity Characteristics:
    • Best-Case Time Complexity: O(n)O(n) — Achieved when the input array is already completely sorted, provided the algorithm incorporates an early-exit tracking flag (a boolean flag that checks whether any swap occurred during the pass; if none occur, it terminates immediately after a single pass of n−1n - 1 comparisons).
    • Average-Case Time Complexity: O(n2)O(n^2) — In typical unsorted states, quadratic operations involving frequent comparisons and positional exchanges are necessary.
    • Worst-Case Time Complexity: O(n2)O(n^2) — Occurs when the input array is structured in reverse sorted order, demanding the maximal theoretical bounds of both comparisons and swaps:     ∑i=1n−1i=n(n−1)2\sum_{i=1}^{n-1} i = \frac{n(n - 1)}{2}
    • Space Complexity: O(1)O(1) — Conserves memory by operating entirely in-place, relying exclusively on a constant number of temporary variables for handling exchanges.

Bubble sort multi-pass element comparisons and swaps

  • Concrete Sorting Traces:
    • Example 1 (n=4n = 4):
    • Initial Array: [5,3,8,2][5, 3, 8, 2]
    • Pass 1:
      • Compare 55 and 33: Since 5>35 > 3, perform swap →[3,5,8,2]\rightarrow [3, 5, 8, 2].
      • Compare 55 and 88: Since 5<85 < 8, perform no swap →[3,5,8,2]\rightarrow [3, 5, 8, 2].
      • Compare 88 and 22: Since 8>28 > 2, perform swap →[3,5,2,8]\rightarrow [3, 5, 2, 8].
      • Result of Pass 1: Element 88 is locked at the terminal index.
    • Pass 2:
      • Compare 33 and 55: Since 3<53 < 5, perform no swap →[3,5,2,8]\rightarrow [3, 5, 2, 8].
      • Compare 55 and 22: Since 5>25 > 2, perform swap →[3,2,5,8]\rightarrow [3, 2, 5, 8].
      • Result of Pass 2: Element 55 is locked at index 22.
    • Pass 3:
      • Compare 33 and 22: Since 3>23 > 2, perform swap →[2,3,5,8]\rightarrow [2, 3, 5, 8].
    • Final Sorted Array: [2,3,5,8][2, 3, 5, 8].
    • Example 2 (n=6n = 6):
    • Initial Array: [1,6,3,4,5,2][1, 6, 3, 4, 5, 2]
    • Pass 1 Step-by-Step:
      • Step 1: Compare index 00 and index 11 (11 and 66) →\rightarrow Do not swap (1<61 < 6).
      • Step 2: Compare index 11 and index 22 (66 and 33) →\rightarrow Swap (3<63 < 6) →[1,3,6,4,5,2]\rightarrow [1, 3, 6, 4, 5, 2].
      • Step 3: Compare index 22 and index 33 (66 and 44) →\rightarrow Swap (4<64 < 6) →[1,3,4,6,5,2]\rightarrow [1, 3, 4, 6, 5, 2].
      • Step 4: Compare index 33 and index 44 (66 and 55) →\rightarrow Swap (5<65 < 6) →[1,3,4,5,6,2]\rightarrow [1, 3, 4, 5, 6, 2].
      • Step 5: Compare index 44 and index 55 (66 and 22) →\rightarrow Swap (2<62 < 6) →[1,3,4,5,2,6]\rightarrow [1, 3, 4, 5, 2, 6].
    • Subsequent Iterations: Repeat passes starting from the beginning until an entire pass completes with zero swaps.
    • Example 3 (n=5n = 5):
    • Initial Array: [5,1,4,2,8][5, 1, 4, 2, 8]
    • First Pass:
      • Swap adjacent elements (5,1)→[1,5,4,2,8](5, 1) \rightarrow [1, 5, 4, 2, 8].
      • Swap adjacent elements (5,4)→[1,4,5,2,8](5, 4) \rightarrow [1, 4, 5, 2, 8].
      • Swap adjacent elements (5,2)→[1,4,2,5,8](5, 2) \rightarrow [1, 4, 2, 5, 8].
      • Compare (5,8)→(5, 8) \rightarrow No swap →[1,4,2,5,8]\rightarrow [1, 4, 2, 5, 8].
    • Second Pass:
      • Compare (1,4)→(1, 4) \rightarrow No swap →[1,4,2,5,8]\rightarrow [1, 4, 2, 5, 8].
      • Swap adjacent elements (4,2)→[1,2,4,5,8](4, 2) \rightarrow [1, 2, 4, 5, 8].
      • Compare (4,5)→(4, 5) \rightarrow No swap →[1,2,4,5,8]\rightarrow [1, 2, 4, 5, 8].
      • Compare (5,8)→(5, 8) \rightarrow No swap →[1,2,4,5,8]\rightarrow [1, 2, 4, 5, 8].
    • Third Pass:
      • Compare (1,2)→(1, 2) \rightarrow No swap.
      • Compare (2,4)→(2, 4) \rightarrow No swap.
      • Compare (4,5)→(4, 5) \rightarrow No swap.
      • Compare (5,8)→(5, 8) \rightarrow No swap.
      • Zero swaps triggered; array is declared sorted: [1,2,4,5,8][1, 2, 4, 5, 8].

Selection Sort

  • Conceptual Framework: An in-place comparison sort that divides the array logically into a sorted left sub-array and an unsorted right sub-array. It repeatedly finds the smallest (or largest) element from the unsorted sub-array and swaps it into its proper position at the boundary of the sorted region.
  • Algorithmic Procedure:
    • Step 1: Initialize the sorted boundary at the first element (index 0\text{index } 0).
    • Step 2: Assume the first element of the unsorted segment is the absolute minimum (min_index=i\text{min\_index} = i).
    • Step 3: Sequentially iterate through all remaining unsorted elements (j=i+1j = i + 1 to n−1n - 1), comparing each against the value at min_index\text{min\_index}.
    • Step 4: If any element is smaller than the current minimum, update min_index\text{min\_index} to point to that element's location.
    • Step 5: Upon scanning the unsorted segment, swap the element at min_index\text{min\_index} with the element at index ii.
    • Step 6: Increment index ii and repeat until the array is fully sorted.
  • Algorithmic Advantages:
    • Structurally simple, intuitive, and easy to implement.
    • Well suited for small datasets.
    • Minimizes memory write operations by performing significantly fewer swaps than Bubble Sort (strictly at most n−1n - 1 total swaps).
    • Minimal auxiliary memory overhead, maintaining O(1)O(1) extra space.
  • Complexity Analysis:
    • Best-Case Time Complexity: O(n2)O(n^2) — Even if the array is already sorted, the algorithm lacks an early exit mechanism and must perform every comparison across all passes to verify the minimum element.
    • Average-Case Time Complexity: O(n2)O(n^2) — Requires continuous quadratic scans to locate the minimum element in each pass.
    • Worst-Case Time Complexity: O(n2)O(n^2) — Performs the exact same number of comparisons regardless of initial ordering (including reverse-sorted data):     n(n−1)2 comparisons\frac{n(n - 1)}{2} \text{ comparisons}
    • Space Complexity: O(1)O(1) — Requires constant auxiliary storage strictly for indices tracking the minimum element and conducting positional swaps.

Selection sort step-by-step minimum selection and swapping

  • Concrete Sorting Traces:
    • Example 1 (n=8n = 8):
    • Unsorted List: [15,20,10,30,50,18,5,45][15, 20, 10, 30, 50, 18, 5, 45]
    • Iteration #1 (Target Position: Index 0):
      • Compare 15>20→FALSE15 > 20 \rightarrow \text{FALSE}.
      • Compare 15>10→TRUE→15 > 10 \rightarrow \text{TRUE} \rightarrow Swap →[10,20,15,30,50,18,5,45]\rightarrow [10, 20, 15, 30, 50, 18, 5, 45].
      • Compare 10>30→FALSE10 > 30 \rightarrow \text{FALSE}.
      • Compare 10>50→FALSE10 > 50 \rightarrow \text{FALSE}.
      • Compare 10>18→FALSE10 > 18 \rightarrow \text{FALSE}.
      • Compare 10>5→TRUE→10 > 5 \rightarrow \text{TRUE} \rightarrow Swap →[5,20,15,30,50,18,10,45]\rightarrow [5, 20, 15, 30, 50, 18, 10, 45].
      • Compare 5>45→FALSE5 > 45 \rightarrow \text{FALSE}.
      • Array after Iteration 1: [5,20,15,30,50,18,10,45][5, 20, 15, 30, 50, 18, 10, 45].
    • Iteration #2 (Target Position: Index 1): Scan from index 11; smallest element found is 1010. Swap with index 11 →[5,10,20,30,50,18,15,45]\rightarrow [5, 10, 20, 30, 50, 18, 15, 45].
    • Iteration #3 (Target Position: Index 2): Scan from index 22; smallest element found is 1515. Swap with index 22 →[5,10,15,30,50,20,18,45]\rightarrow [5, 10, 15, 30, 50, 20, 18, 45].
    • Iteration #4 (Target Position: Index 3): Scan from index 33; smallest element found is 1818. Swap with index 33 →[5,10,15,18,50,30,20,45]\rightarrow [5, 10, 15, 18, 50, 30, 20, 45].
    • Iteration #5 (Target Position: Index 4): Scan from index 44; smallest element found is 2020. Swap with index 44 →[5,10,15,18,20,50,30,45]\rightarrow [5, 10, 15, 18, 20, 50, 30, 45].
    • Iteration #6 (Target Position: Index 5): Scan from index 55; smallest element found is 3030. Swap with index 55 →[5,10,15,18,20,30,50,45]\rightarrow [5, 10, 15, 18, 20, 30, 50, 45].
    • Iteration #7 (Target Position: Index 6): Scan from index 66; smallest element found is 4545. Swap with index 66 →[5,10,15,18,20,30,45,50]\rightarrow [5, 10, 15, 18, 20, 30, 45, 50].
    • Final Result: Sorted list is [5,10,15,18,20,30,45,50][5, 10, 15, 18, 20, 30, 45, 50].
    • Example 2 (n=5n = 5):
    • Initial Array: [5,2,9,6,4][5, 2, 9, 6, 4]
    • Pass 1: Target index 00; minimum element identified is 22 →\rightarrow Swap with 5→[2,5,9,6,4]5 \rightarrow [2, 5, 9, 6, 4].
    • Pass 2: Target index 11; minimum element identified is 44 →\rightarrow Swap with 5→[2,4,9,6,5]5 \rightarrow [2, 4, 9, 6, 5].
    • Pass 3: Target index 22; minimum element identified is 55 →\rightarrow Swap with 9→[2,4,5,6,9]9 \rightarrow [2, 4, 5, 6, 9].
    • Pass 4: Target index 33; minimum element identified is 66 →\rightarrow No swap required →[2,4,5,6,9]\rightarrow [2, 4, 5, 6, 9].
    • Example 3 (n=9n = 9):
    • Initial Array: [29,72,98,13,87,66,52,51,36][29, 72, 98, 13, 87, 66, 52, 51, 36]
    • Pass 1: 1313 is smallest →\rightarrow Swap with 29→[13,72,98,29,87,66,52,51,36]29 \rightarrow [13, 72, 98, 29, 87, 66, 52, 51, 36].
    • Pass 2: 2929 is smallest in remaining segment →\rightarrow Swap with 72→[13,29,98,72,87,66,52,51,36]72 \rightarrow [13, 29, 98, 72, 87, 66, 52, 51, 36].
    • Pass 3: 3636 is smallest in remaining segment →\rightarrow Swap with 98→[13,29,36,72,87,66,52,51,98]98 \rightarrow [13, 29, 36, 72, 87, 66, 52, 51, 98].
    • Pass 4: 5151 is smallest in remaining segment →\rightarrow Swap with 72→[13,29,36,51,87,66,52,72,98]72 \rightarrow [13, 29, 36, 51, 87, 66, 52, 72, 98].
    • Pass 5: 5252 is smallest in remaining segment →\rightarrow Swap with 87→[13,29,36,51,52,66,87,72,98]87 \rightarrow [13, 29, 36, 51, 52, 66, 87, 72, 98].
    • Pass 6: 6666 is smallest in remaining segment →\rightarrow No swapping needed →[13,29,36,51,52,66,87,72,98]\rightarrow [13, 29, 36, 51, 52, 66, 87, 72, 98].
    • Pass 7: 7272 is smallest in remaining segment →\rightarrow Swap with 87→[13,29,36,51,52,66,72,87,98]87 \rightarrow [13, 29, 36, 51, 52, 66, 72, 87, 98].
    • Pass 8: 8787 is smallest in remaining segment →\rightarrow No swapping needed →[13,29,36,51,52,66,72,87,98]\rightarrow [13, 29, 36, 51, 52, 66, 72, 87, 98].
    • Final State: Sorting completed successfully.

Merge Sort

  • Algorithmic Paradigm: A classic Divide and Conquer sorting strategy that recursively segments an array into smaller sub-arrays, sorts them independently, and combines (merges) them to produce a fully sorted output.
  • Foundational Deductions:
    • Sorting small sub-arrays requires fewer computational steps than sorting large arrays directly.
    • Merging two pre-sorted lists requires linear operations (O(n)O(n)), which is substantially more efficient than re-sorting unorganized data from scratch.
  • The Three Divide and Conquer Phases:
    • Divide: Partition the active array into two approximately equal halves by computing the central midpoint index.
    • Conquer: Recursively apply Merge Sort to independently sort both the left and right sub-arrays.
    • Merge: Systematically compare and merge the two sorted sub-arrays into a single, cohesive sorted array.
  • Recursive Termination Condition:
    • Base Case: If the length of an array is 00 or 11, it is trivially sorted by definition; the recursion unwinds immediately.
  • Complexity Analysis:
    • Best-Case Time Complexity: O(nlog⁡(n))O(n \log(n)) — The array is split evenly through logarithmic levels (log⁡2(n)\log_2(n)) and merged in linear time (O(n)O(n)) at each level.
    • Average-Case Time Complexity: O(nlog⁡(n))O(n \log(n)) — Consistently performs logarithmic divisions and linear merging across all average distributions.
    • Worst-Case Time Complexity: O(nlog⁡(n))O(n \log(n)) — Preserves strict O(nlog⁡(n))O(n \log(n)) asymptotic performance even when processing reverse-sorted inputs, avoiding the performance degradation seen in Quick Sort.
    • Space Complexity: O(n)O(n) — Standard array-based implementations require auxiliary memory proportional to the array size to hold merged elements temporarily before writing back.

Merge sort divide-and-conquer binary splitting and merging tree

  • Concrete Execution Traces:
    • Example 1 (n=4n = 4):
    • Unsorted Array: [70,30,50,10][70, 30, 50, 10]
    • Divide Phase:
      • Split into sub-arrays: [70,30][70, 30] and [50,10][50, 10].
      • Subdivide into atomic elements: [70][70], [30][30] and [50][50], [10][10].
    • Conquer & Merge Phase:
      • Merge [70][70] and [30]→[30,70][30] \rightarrow [30, 70].
      • Merge [50][50] and [10]→[10,50][10] \rightarrow [10, 50].
      • Merge sorted halves [30,70][30, 70] and [10,50]→[10,30,50,70][10, 50] \rightarrow [10, 30, 50, 70].
    • Sorted Array: [10,30,50,70][10, 30, 50, 70].
    • Example 2 (n=6n = 6):
    • Initial Array: [6,5,12,10,9,1][6, 5, 12, 10, 9, 1]
    • Decomposition:
      • Split into [6,5,12][6, 5, 12] and [10,9,1][10, 9, 1].
      • Left side splits into [6][6] and [5,12]→[5][5, 12] \rightarrow [5] and [12][12].
      • Right side splits into [10][10] and [9,1]→[9][9, 1] \rightarrow [9] and [1][1].
    • Recomposition:
      • Recombine [5][5] and [12]→[5,12][12] \rightarrow [5, 12].
      • Recombine [6][6] and [5,12]→[5,6,12][5, 12] \rightarrow [5, 6, 12].
      • Recombine [9][9] and [1]→[1,9][1] \rightarrow [1, 9].
      • Recombine [10][10] and [1,9]→[1,9,10][1, 9] \rightarrow [1, 9, 10].
      • Final merge of [5,6,12][5, 6, 12] and [1,9,10]→[1,5,6,9,10,12][1, 9, 10] \rightarrow [1, 5, 6, 9, 10, 12].
    • Example 3 (n=8n = 8):
    • Initial Array: [5,2,4,7,1,3,2,6][5, 2, 4, 7, 1, 3, 2, 6]
    • Level 1 Split: [5,2,4,7][5, 2, 4, 7] and [1,3,2,6][1, 3, 2, 6].
    • Level 2 Split: Pairs [5,2][5, 2], [4,7][4, 7], [1,3][1, 3], and [2,6][2, 6].
    • Level 3 Split: Single elements [5],[2],[4],[7],[1],[3],[2],[6][5], [2], [4], [7], [1], [3], [2], [6].
    • Level 2 Merge: [2,5][2, 5], [4,7][4, 7], [1,3][1, 3], and [2,6][2, 6].
    • Level 1 Merge: Combined into [2,4,5,7][2, 4, 5, 7] and [1,2,3,6][1, 2, 3, 6].
    • Level 0 Merge: Final sorted array [1,2,2,3,4,5,6,7][1, 2, 2, 3, 4, 5, 6, 7].

Insertion Sort

  • Core Definition: An intuitive, in-place sorting algorithm that builds the final sorted array incrementally by examining one element per pass and inserting it into its correct position within the already sorted portion of the array.
  • Playing Cards Analogy: Replicates the natural method people use to arrange playing cards in their hands: holding sorted cards in one hand, picking an unsorted card from the table, scanning the sorted set from right to left, and sliding it into its appropriate position.
  • Operational Mechanics:
    • Logically divides the collection into a sorted partition and an unsorted partition.
    • Operates on an array of nn elements:
    • Initially, the element at index 00 is treated as a sorted sub-array of size 11.
    • The unsorted partition spans from index 11 through n−1n - 1.
    • During each pass, the first value of the unsorted segment (the target key) is selected.
    • The algorithm scans backward through the sorted partition; every element larger than the key is shifted one index position to the right.
    • Once an element smaller than or equal to the key (or the start of the array) is reached, the key is inserted into the resulting empty slot.
  • Practical Strengths & Trade-offs:
    • Highly efficient on small input sets.
    • Excellent performance on partially or nearly sorted datasets.
    • Operates strictly in-place, preserving system memory.
    • Serves as an online sorting algorithm, meaning it can process and integrate new data elements as they arrive in real time without restarting.
    • Outperformed by advanced O(nlog⁡(n))O(n \log(n)) algorithms (such as Quick Sort, Merge Sort, and Heap Sort) on massive, randomly distributed datasets.
  • Complexity Analysis:
    • Best-Case Time Complexity: O(n)O(n) — Occurs when the input array is already sorted; each element only requires a single comparison against its predecessor, triggering zero displacement shifts.
    • Average-Case Time Complexity: O(n2)O(n^2) — On arbitrary inputs, elements typically undergo multiple comparisons and shifts to reach their proper positions.
    • Worst-Case Time Complexity: O(n2)O(n^2) — Occurs when the input is sorted in reverse order; each newly evaluated element must be compared against and shifted past every item in the sorted partition.
    • Space Complexity: O(1)O(1) — Conserves memory with strictly in-place operations, utilizing constant auxiliary space for scalar variables like the insertion key and index counters.

Insertion sort progressive shifting and inserting into sorted subarray

  • Concrete Execution Traces:
    • Example 1 (n=5n = 5):
    • Initial Array: [23,1,10,5,2][23, 1, 10, 5, 2]
    • Pass 1: Index 00 ([23][23]) is considered sorted.
    • Pass 2: Evaluate element 11. It is smaller than 2323, so 2323 shifts right and 11 is inserted at the front →[1,23,10,5,2]\rightarrow [1, 23, 10, 5, 2].
    • Pass 3: Evaluate element 1010. Compare with 2323 (23>1023 > 10, so 2323 shifts right); compare with 11 (1<101 < 10, insertion position found) →[1,10,23,5,2]\rightarrow [1, 10, 23, 5, 2].
    • Pass 4: Evaluate element 55. Shifts 2323 and 1010 one position right; inserts 55 directly after 1→[1,5,10,23,2]1 \rightarrow [1, 5, 10, 23, 2].
    • Pass 5: Evaluate element 22. Shifts 23,10,523, 10, 5 right; inserts 22 directly after 1→[1,2,5,10,23]1 \rightarrow [1, 2, 5, 10, 23].
    • Example 2 (n=6n = 6):
    • Initial Array: [5,4,2,1,6,3][5, 4, 2, 1, 6, 3]
    • Initial condition: First element (55) is considered sorted.
    • Step 1: Element 44 is inserted before 55; 55 moves one position forward →[4,5,2,1,6,3]\rightarrow [4, 5, 2, 1, 6, 3].
    • Step 2: Element 22 is inserted before 44; 44 and 55 move one position forward →[2,4,5,1,6,3]\rightarrow [2, 4, 5, 1, 6, 3].
    • Step 3: Element 11 is inserted before 22; remaining elements shift forward →[1,2,4,5,6,3]\rightarrow [1, 2, 4, 5, 6, 3].
    • Step 4: Element 66 is evaluated; since 6>56 > 5, it is automatically in the correct place →[1,2,4,5,6,3]\rightarrow [1, 2, 4, 5, 6, 3].
    • Step 5: Element 33 is inserted before 44; elements 4,5,64, 5, 6 shift forward →[1,2,3,4,5,6]\rightarrow [1, 2, 3, 4, 5, 6].
    • Example 3 (n=8n = 8):
    • Initial Array: [4,3,2,10,12,1,5,6][4, 3, 2, 10, 12, 1, 5, 6]
    • Systematic insertion steps:
      • Insert 3→[3,4,2,10,12,1,5,6]3 \rightarrow [3, 4, 2, 10, 12, 1, 5, 6]
      • Insert 2→[2,3,4,10,12,1,5,6]2 \rightarrow [2, 3, 4, 10, 12, 1, 5, 6]
      • Evaluate 10→10 \rightarrow Remains in place →[2,3,4,10,12,1,5,6]\rightarrow [2, 3, 4, 10, 12, 1, 5, 6]
      • Evaluate 12→12 \rightarrow Remains in place →[2,3,4,10,12,1,5,6]\rightarrow [2, 3, 4, 10, 12, 1, 5, 6]
      • Insert 1→1 \rightarrow Shifts 12,10,4,3,212, 10, 4, 3, 2 right →[1,2,3,4,10,12,5,6]\rightarrow [1, 2, 3, 4, 10, 12, 5, 6]
      • Insert 5→5 \rightarrow Shifts 12,1012, 10 right →[1,2,3,4,5,10,12,6]\rightarrow [1, 2, 3, 4, 5, 10, 12, 6]
      • Insert 6→6 \rightarrow Shifts 12,1012, 10 right →[1,2,3,4,5,6,10,12]\rightarrow [1, 2, 3, 4, 5, 6, 10, 12]

Quick Sort (Partition Exchange Sort)

  • Alternate Nomenclature: Formally known as Partition Exchange Sort.
  • Foundational Framework: A high-performance sorting algorithm governed by the Divide and Conquer strategy. It selects a designated "pivot" element and partitions the surrounding array such that elements smaller than the pivot are placed before it and elements larger than the pivot are placed after it.
  • Three Essential Execution Phases:
    • Phase 1 (Select a Pivot): Choose an element from the array to serve as the pivot reference. Common selection strategies include choosing the first element, terminal element, middle element, or a randomized value.
    • Phase 2 (Partition the Array): Rearrange elements such that all values smaller than the pivot precede it, and all values greater than the pivot succeed it. Upon completion of partitioning, the pivot occupies its final, correct sorted index.
    • Phase 3 (Recursively Sort): Recursively apply the exact same partitioning logic to the independent left and right sub-arrays until the base case of sub-arrays containing zero or one element is satisfied.

Quick sort partitioning and split point determination

  • Partitioning Procedure (First Element as Pivot):
    • Step 1: Initialize pointers: loc=0\text{loc} = 0, left=0\text{left} = 0, and right=n−1\text{right} = n - 1.
    • Step 2: Scan the array from right to left, comparing elements with the pivot value at loc\text{loc}.
    • Step 3: If an element smaller than the pivot is encountered (A[right]<pivotA[\text{right}] < \text{pivot}), swap that element with the pivot and update the tracking pointer: loc=right\text{loc} = \text{right}.
    • Step 4: Reverse the direction and scan from left to right, comparing elements with the pivot.
    • Step 5: If an element larger than the pivot is encountered (A[left]>pivotA[\text{left}] > \text{pivot}), swap that element with the pivot and update the tracking pointer: loc=left\text{loc} = \text{left}.
    • Step 6: Repeat these alternating directional scans until the two scanning pointers converge (left=right\text{left} = \text{right}). The pivot is now fixed in its permanent, correct location.
    • Step 7: Recursively invoke Quick Sort on the independent left sub-array and right sub-array.

Quick sort two-pointer convergence partitioning

  • Alternative Partitioning Procedure (Two-Pointer Convergence / Hoare Variant):
    • Set the first element as the pivot value.
    • Advance the leftmark\text{leftmark} pointer to the right as long as elements are smaller than the pivot (A[leftmark]<pivotA[\text{leftmark}] < \text{pivot}; stop when A[leftmark]>pivotA[\text{leftmark}] > \text{pivot}).
    • Retreat the rightmark\text{rightmark} pointer to the left as long as elements are larger than the pivot (A[rightmark]>pivotA[\text{rightmark}] > \text{pivot}; stop when A[rightmark]<pivotA[\text{rightmark}] < \text{pivot}).
    • If leftmark<rightmark\text{leftmark} < \text{rightmark}, exchange the values at leftmark\text{leftmark} and rightmark\text{rightmark}.
    • When the pointers cross (rightmark<leftmark\text{rightmark} < \text{leftmark}), swap the pivot with the value at rightmark\text{rightmark}. The position at rightmark\text{rightmark} becomes the split point.
  • Complexity Analysis:
    • Best-Case Time Complexity: O(nlog⁡(n))O(n \log(n)) — Occurs when the chosen pivot consistently divides the sub-arrays into nearly equal halves, producing a balanced recursion tree of depth log⁡2(n)\log_2(n).
    • Average-Case Time Complexity: O(nlog⁡(n))O(n \log(n)) — Occurs under typical randomized distributions where partitions remain reasonably balanced.
    • Worst-Case Time Complexity: O(n2)O(n^2) — Occurs when the pivot selection consistently produces maximally unbalanced partitions (e.g., partitioning an array of size nn into sub-arrays of size 00 and n−1n - 1). This happens when the array is already sorted (in ascending or descending order) and the first element is routinely selected as the pivot.
  • Concrete Execution Traces:
    • Example 1 (n=9n = 9):
    • Unsorted Array: A[9]=[51,95,66,72,42,38,39,41,15]A[9] = [51, 95, 66, 72, 42, 38, 39, 41, 15]
    • Chosen Pivot Value: 5151 (situated at index 00)
    • Partitioning Steps:
      • Initial state check: Element at index 11 (9595) is >51> 51; element at index 88 (1515) is <51< 51. Swap positions 11 and 8→[51,15,66,72,42,38,39,41,95]8 \rightarrow [51, 15, 66, 72, 42, 38, 39, 41, 95].
      • Subsequent check: Element at index 22 (6666) is >51> 51; element at index 77 (4141) is <51< 51. Swap positions 22 and 7→[51,15,41,72,42,38,39,66,95]7 \rightarrow [51, 15, 41, 72, 42, 38, 39, 66, 95].
      • Subsequent check: Element at index 33 (7272) is >51> 51; element at index 66 (3939) is <51< 51. Swap positions 33 and 6→[51,15,41,39,42,38,72,66,95]6 \rightarrow [51, 15, 41, 39, 42, 38, 72, 66, 95].
      • Center convergence check: Elements at index 44 (4242) and index 55 (3838) are both <51< 51. Pointers cross and halt.
      • Finalize split point: Swap pivot (5151) with the value at the split point (3838) →[38,15,41,39,42,51,72,66,95]\rightarrow [38, 15, 41, 39, 42, 51, 72, 66, 95].
    • Resulting Partitioned State:
      • Left sub-array (<51< 51): [38,15,41,39,42][38, 15, 41, 39, 42] (size 55)
      • Correctly placed pivot: 5151 at index 55
      • Right sub-array (>51> 51): [72,66,95][72, 66, 95] (size 33)
    • Example 2 (n=9n = 9):
    • Array: [54,26,93,17,77,31,44,55,20][54, 26, 93, 17, 77, 31, 44, 55, 20]
    • Pivot Selected: 5454
    • Two-Pointer Convergence Process:
      • Advance leftmark\text{leftmark}: 26<5426 < 54 (advances); stops at 93>5493 > 54.
      • Advance rightmark\text{rightmark}: Stops immediately at 20<5420 < 54.
      • Exchange values at leftmark\text{leftmark} and rightmark\text{rightmark} (9393 and 2020) →[54,26,20,17,77,31,44,55,93]\rightarrow [54, 26, 20, 17, 77, 31, 44, 55, 93].
      • Advance leftmark\text{leftmark} past 1717; stops at 77>5477 > 54.
      • Advance rightmark\text{rightmark} past 5555; stops at 44<5444 < 54.
      • Exchange values at leftmark\text{leftmark} and rightmark\text{rightmark} (7777 and 4444) →[54,26,20,17,44,31,77,55,93]\rightarrow [54, 26, 20, 17, 44, 31, 77, 55, 93].
      • Advance leftmark\text{leftmark}; stops at 77>5477 > 54.
      • Advance rightmark\text{rightmark}; stops at 31<5431 < 54.
      • Pointers cross (rightmark<leftmark\text{rightmark} < \text{leftmark}); split point confirmed at rightmark\text{rightmark} (holding 3131).
      • Exchange pivot (5454) with 31→[31,26,20,17,44,54,77,55,93]31 \rightarrow [31, 26, 20, 17, 44, 54, 77, 55, 93].
    • Resulting Partitioned State: Pivot 5454 is fixed in its final sorted position at index 55, flanked by a left sub-array of smaller values and a right sub-array of larger values.