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).
- Step 2: Compare the value of the current array element with the search key (VAL or 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) — Occurs when the target key is located at the first position of the array (index 0), requiring exactly one comparison.
- Average-Case Time Complexity: O(n) — On average across arbitrary distributions, the algorithm inspects approximately half of the total elements (2n comparisons).
- Worst-Case Time Complexity: O(n) — Occurs when the target key is situated at the terminal position (index n−1) or is completely absent from the array, necessitating a full traversal of all n elements.
- Space Complexity: 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 (n).

- Demonstrative Walkthroughs:
- Introductory Example (n=10):
- Array: {10,8,2,7,3,4,9,1,6,5}
- Target: VAL=7
- Traversal: Index 0 (10)→Index 1 (8)→Index 2 (2)→Index 3 (7)
- Result: Element found at position 3 (using zero-based indexing).
- Trace Example 1 (n=5):
- Array: [10,25,30,45,50]
- Target: VAL=45
- Sequential Comparisons:
- 25=45
- 30=45
- 45=45
- Result: Element successfully identified at index 3 (the 4th position).
- Trace Example 2 (n=9):
- Array: [29,87,89,21,23,17,11,10,14]
- Target Key: K=17
- Sequential Comparisons:
- Index 0:29=17
- Index 1:87=17
- Index 2:89=17
- Index 3:21=17
- Index 4:23=17
- Index 5:17=17
- Result: Search halts; key is located at index 5.
- Trace Example 3 (n=9):
- Array: [10,50,30,70,80,60,20,90,40]
- Target Key: VAL=20
- Traversal Path: Iterates sequentially through indices 0,1,2,3,4,5 until encountering 20 at index 6.
- Trace Example 4 (n=8):
- Array: [65,20,10,55,32,12,50,99]
- Search Element: 12
- Execution Steps:
- Step 1: Compare search element (12) with first element (65). No match (65=12); increment pointer.
- Step 2: Compare with second element (20). No match (20=12); increment pointer.
- Step 3: Compare with third element (10). No match (10=12); increment pointer.
- Step 4: Compare with fourth element (55). No match (55=12); increment pointer.
- Step 5: Compare with fifth element (32). No match (32=12); increment pointer.
- Step 6: Compare with sixth element (12). Match confirmed (12=12); terminate comparisons and display that the element is found at index 5.
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 (or Low, initialized to 0).
- High Boundary: END (or High, initialized to n−1).
- Midpoint Index Formula:
MID=⌊2BEG+END⌋
- Algorithmic Mechanics:
- Step 1: Compute the middle index MID.
- Step 2: Compare the search target (VAL or key) with the element at the midpoint (A[MID]):
- Condition A (Match): If VAL=A[MID], the search is successful; return POS=MID.
- Condition B (Target is Smaller): If VAL<A[MID], the search space is restricted to the lower/left sub-array; set END=MID−1.
- Condition C (Target is Larger): If VAL>A[MID], the search space is restricted to the upper/right sub-array; set BEG=MID+1.
- Step 3: Re-evaluate and repeat while BEG≤END.
- Step 4 (Termination): If BEG>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 (2kn after k iterations).
- Best-Case Time Complexity: 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)) (specifically O(log2(n))) — Search intervals are recursively halved at each processing step.
- Worst-Case Time Complexity: 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 (⌊log2(n)⌋+1).
- Space Complexity: O(1) — Requires strictly constant extra memory for managing index tracking variables (left/BEG, right/END, and mid/MID).

- Detailed Execution Examples:
- Example 1 (n=11):
- Array: {0,1,2,3,4,5,6,7,8,9,10}
- Target: VAL=9
- Iteration 1: BEG=0, END=10. Midpoint calculation:
MID=⌊20+10⌋=5
Array value: A[5]=5. Compare: 5<9. Target lies in right half; update BEG=MID+1=6.
- Iteration 2: BEG=6, END=10. Midpoint calculation:
MID=⌊26+10⌋=8
Array value: A[8]=8. Compare: 8<9. Target lies in right half; update BEG=MID+1=9.
- Iteration 3: BEG=9, END=10. Midpoint calculation:
MID=⌊29+10⌋=9
Array value: A[9]=9. Compare: 9=9. Match found; return index position POS=9.
- Example 2 (n=10):
- Array: [1,2,3,4,5,6,7,8,9,10] (indices 0 through 9)
- Target Key: 7
- Step 1: Low=0, High=9, Mid=4 (A[4]=5). Since 7>5, eliminate the left half and consider the right sub-array.
- Step 2: Low=5, High=9, Mid=7 (A[7]=8). Since 7<8, eliminate the right half and consider the left sub-array.
- Step 3: Low=5, High=6, Mid=5 (A[5]=6). Since 7>6, consider the right half.
- Step 4: Pointer convergence: Low=Mid=High=6 (A[6]=7). Target is present at index 6.
- Example 3 (n=10):
- Array: [2,5,8,12,16,23,38,56,72,91]
- Target Key: 23
- Step 1: Set L=0, H=9, M=4 (A[4]=16). Because 23>16, proceed to the 2nd half.
- Step 2: Set L=5, H=9, M=7 (A[7]=56). Because 23<56, proceed to the 1st half of the remaining segment.
- Step 3: Set L=5, H=6, M=5 (A[5]=23). Target matched (23=23); terminate and return index 5.
- Example 4 (n=9):
- Array: [10,12,20,32,50,55,65,80,99]
- Case A: Search for element 12:
- Step 1: Compare search element (12) with middle element at index 4 (50). Since 12=50 and 12<50, restrict search space to left sublist: {10,12,20,32}.
- Step 2: Compute midpoint of left sublist; middle element at index 1 is 12. Since 12=12, search succeeds with message: "Element found at index 1".
- Case B: Search for element 80:
- Step 1: Compare search element (80) with middle element at index 4 (50). Since 80=50 and 80>50, restrict search space to right sublist: {55,65,80,99}.
- Step 2: Compare search element (80) with middle element of sublist at index 6 (65). Since 80=65 and 80>65, restrict search space to remaining right sublist: {80,99}.
- Step 3: Compare search element (80) with middle element at index 7 (80). 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 k, the k-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).
- 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]), 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) — 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−1 comparisons).
- Average-Case Time Complexity: O(n2) — In typical unsorted states, quadratic operations involving frequent comparisons and positional exchanges are necessary.
- Worst-Case Time Complexity: O(n2) — Occurs when the input array is structured in reverse sorted order, demanding the maximal theoretical bounds of both comparisons and swaps:
∑i=1n−1i=2n(n−1)
- Space Complexity: O(1) — Conserves memory by operating entirely in-place, relying exclusively on a constant number of temporary variables for handling exchanges.

- Concrete Sorting Traces:
- Example 1 (n=4):
- Initial Array: [5,3,8,2]
- Pass 1:
- Compare 5 and 3: Since 5>3, perform swap →[3,5,8,2].
- Compare 5 and 8: Since 5<8, perform no swap →[3,5,8,2].
- Compare 8 and 2: Since 8>2, perform swap →[3,5,2,8].
- Result of Pass 1: Element 8 is locked at the terminal index.
- Pass 2:
- Compare 3 and 5: Since 3<5, perform no swap →[3,5,2,8].
- Compare 5 and 2: Since 5>2, perform swap →[3,2,5,8].
- Result of Pass 2: Element 5 is locked at index 2.
- Pass 3:
- Compare 3 and 2: Since 3>2, perform swap →[2,3,5,8].
- Final Sorted Array: [2,3,5,8].
- Example 2 (n=6):
- Initial Array: [1,6,3,4,5,2]
- Pass 1 Step-by-Step:
- Step 1: Compare index 0 and index 1 (1 and 6) → Do not swap (1<6).
- Step 2: Compare index 1 and index 2 (6 and 3) → Swap (3<6) →[1,3,6,4,5,2].
- Step 3: Compare index 2 and index 3 (6 and 4) → Swap (4<6) →[1,3,4,6,5,2].
- Step 4: Compare index 3 and index 4 (6 and 5) → Swap (5<6) →[1,3,4,5,6,2].
- Step 5: Compare index 4 and index 5 (6 and 2) → Swap (2<6) →[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=5):
- Initial Array: [5,1,4,2,8]
- First Pass:
- Swap adjacent elements (5,1)→[1,5,4,2,8].
- Swap adjacent elements (5,4)→[1,4,5,2,8].
- Swap adjacent elements (5,2)→[1,4,2,5,8].
- Compare (5,8)→ No swap →[1,4,2,5,8].
- Second Pass:
- Compare (1,4)→ No swap →[1,4,2,5,8].
- Swap adjacent elements (4,2)→[1,2,4,5,8].
- Compare (4,5)→ No swap →[1,2,4,5,8].
- Compare (5,8)→ No swap →[1,2,4,5,8].
- Third Pass:
- Compare (1,2)→ No swap.
- Compare (2,4)→ No swap.
- Compare (4,5)→ No swap.
- Compare (5,8)→ No swap.
- Zero swaps triggered; array is declared sorted: [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).
- Step 2: Assume the first element of the unsorted segment is the absolute minimum (min_index=i).
- Step 3: Sequentially iterate through all remaining unsorted elements (j=i+1 to n−1), comparing each against the value at min_index.
- Step 4: If any element is smaller than the current minimum, update min_index to point to that element's location.
- Step 5: Upon scanning the unsorted segment, swap the element at min_index with the element at index i.
- Step 6: Increment index i 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−1 total swaps).
- Minimal auxiliary memory overhead, maintaining O(1) extra space.
- Complexity Analysis:
- Best-Case Time Complexity: O(n2) — 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) — Requires continuous quadratic scans to locate the minimum element in each pass.
- Worst-Case Time Complexity: O(n2) — Performs the exact same number of comparisons regardless of initial ordering (including reverse-sorted data):
2n(n−1) comparisons
- Space Complexity: O(1) — Requires constant auxiliary storage strictly for indices tracking the minimum element and conducting positional swaps.

- Concrete Sorting Traces:
- Example 1 (n=8):
- Unsorted List: [15,20,10,30,50,18,5,45]
- Iteration #1 (Target Position: Index 0):
- Compare 15>20→FALSE.
- Compare 15>10→TRUE→ Swap →[10,20,15,30,50,18,5,45].
- Compare 10>30→FALSE.
- Compare 10>50→FALSE.
- Compare 10>18→FALSE.
- Compare 10>5→TRUE→ Swap →[5,20,15,30,50,18,10,45].
- Compare 5>45→FALSE.
- Array after Iteration 1: [5,20,15,30,50,18,10,45].
- Iteration #2 (Target Position: Index 1): Scan from index 1; smallest element found is 10. Swap with index 1 →[5,10,20,30,50,18,15,45].
- Iteration #3 (Target Position: Index 2): Scan from index 2; smallest element found is 15. Swap with index 2 →[5,10,15,30,50,20,18,45].
- Iteration #4 (Target Position: Index 3): Scan from index 3; smallest element found is 18. Swap with index 3 →[5,10,15,18,50,30,20,45].
- Iteration #5 (Target Position: Index 4): Scan from index 4; smallest element found is 20. Swap with index 4 →[5,10,15,18,20,50,30,45].
- Iteration #6 (Target Position: Index 5): Scan from index 5; smallest element found is 30. Swap with index 5 →[5,10,15,18,20,30,50,45].
- Iteration #7 (Target Position: Index 6): Scan from index 6; smallest element found is 45. Swap with index 6 →[5,10,15,18,20,30,45,50].
- Final Result: Sorted list is [5,10,15,18,20,30,45,50].
- Example 2 (n=5):
- Initial Array: [5,2,9,6,4]
- Pass 1: Target index 0; minimum element identified is 2 → Swap with 5→[2,5,9,6,4].
- Pass 2: Target index 1; minimum element identified is 4 → Swap with 5→[2,4,9,6,5].
- Pass 3: Target index 2; minimum element identified is 5 → Swap with 9→[2,4,5,6,9].
- Pass 4: Target index 3; minimum element identified is 6 → No swap required →[2,4,5,6,9].
- Example 3 (n=9):
- Initial Array: [29,72,98,13,87,66,52,51,36]
- Pass 1: 13 is smallest → Swap with 29→[13,72,98,29,87,66,52,51,36].
- Pass 2: 29 is smallest in remaining segment → Swap with 72→[13,29,98,72,87,66,52,51,36].
- Pass 3: 36 is smallest in remaining segment → Swap with 98→[13,29,36,72,87,66,52,51,98].
- Pass 4: 51 is smallest in remaining segment → Swap with 72→[13,29,36,51,87,66,52,72,98].
- Pass 5: 52 is smallest in remaining segment → Swap with 87→[13,29,36,51,52,66,87,72,98].
- Pass 6: 66 is smallest in remaining segment → No swapping needed →[13,29,36,51,52,66,87,72,98].
- Pass 7: 72 is smallest in remaining segment → Swap with 87→[13,29,36,51,52,66,72,87,98].
- Pass 8: 87 is smallest in remaining segment → No swapping needed →[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)), 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 0 or 1, it is trivially sorted by definition; the recursion unwinds immediately.
- Complexity Analysis:
- Best-Case Time Complexity: O(nlog(n)) — The array is split evenly through logarithmic levels (log2(n)) and merged in linear time (O(n)) at each level.
- Average-Case Time Complexity: O(nlog(n)) — Consistently performs logarithmic divisions and linear merging across all average distributions.
- Worst-Case Time Complexity: O(nlog(n)) — Preserves strict O(nlog(n)) asymptotic performance even when processing reverse-sorted inputs, avoiding the performance degradation seen in Quick Sort.
- Space Complexity: O(n) — Standard array-based implementations require auxiliary memory proportional to the array size to hold merged elements temporarily before writing back.

- Concrete Execution Traces:
- Example 1 (n=4):
- Unsorted Array: [70,30,50,10]
- Divide Phase:
- Split into sub-arrays: [70,30] and [50,10].
- Subdivide into atomic elements: [70], [30] and [50], [10].
- Conquer & Merge Phase:
- Merge [70] and [30]→[30,70].
- Merge [50] and [10]→[10,50].
- Merge sorted halves [30,70] and [10,50]→[10,30,50,70].
- Sorted Array: [10,30,50,70].
- Example 2 (n=6):
- Initial Array: [6,5,12,10,9,1]
- Decomposition:
- Split into [6,5,12] and [10,9,1].
- Left side splits into [6] and [5,12]→[5] and [12].
- Right side splits into [10] and [9,1]→[9] and [1].
- Recomposition:
- Recombine [5] and [12]→[5,12].
- Recombine [6] and [5,12]→[5,6,12].
- Recombine [9] and [1]→[1,9].
- Recombine [10] and [1,9]→[1,9,10].
- Final merge of [5,6,12] and [1,9,10]→[1,5,6,9,10,12].
- Example 3 (n=8):
- Initial Array: [5,2,4,7,1,3,2,6]
- Level 1 Split: [5,2,4,7] and [1,3,2,6].
- Level 2 Split: Pairs [5,2], [4,7], [1,3], and [2,6].
- Level 3 Split: Single elements [5],[2],[4],[7],[1],[3],[2],[6].
- Level 2 Merge: [2,5], [4,7], [1,3], and [2,6].
- Level 1 Merge: Combined into [2,4,5,7] and [1,2,3,6].
- Level 0 Merge: Final sorted array [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 n elements:
- Initially, the element at index 0 is treated as a sorted sub-array of size 1.
- The unsorted partition spans from index 1 through n−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)) algorithms (such as Quick Sort, Merge Sort, and Heap Sort) on massive, randomly distributed datasets.
- Complexity Analysis:
- Best-Case Time Complexity: 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) — On arbitrary inputs, elements typically undergo multiple comparisons and shifts to reach their proper positions.
- Worst-Case Time Complexity: O(n2) — 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) — Conserves memory with strictly in-place operations, utilizing constant auxiliary space for scalar variables like the insertion key and index counters.

- Concrete Execution Traces:
- Example 1 (n=5):
- Initial Array: [23,1,10,5,2]
- Pass 1: Index 0 ([23]) is considered sorted.
- Pass 2: Evaluate element 1. It is smaller than 23, so 23 shifts right and 1 is inserted at the front →[1,23,10,5,2].
- Pass 3: Evaluate element 10. Compare with 23 (23>10, so 23 shifts right); compare with 1 (1<10, insertion position found) →[1,10,23,5,2].
- Pass 4: Evaluate element 5. Shifts 23 and 10 one position right; inserts 5 directly after 1→[1,5,10,23,2].
- Pass 5: Evaluate element 2. Shifts 23,10,5 right; inserts 2 directly after 1→[1,2,5,10,23].
- Example 2 (n=6):
- Initial Array: [5,4,2,1,6,3]
- Initial condition: First element (5) is considered sorted.
- Step 1: Element 4 is inserted before 5; 5 moves one position forward →[4,5,2,1,6,3].
- Step 2: Element 2 is inserted before 4; 4 and 5 move one position forward →[2,4,5,1,6,3].
- Step 3: Element 1 is inserted before 2; remaining elements shift forward →[1,2,4,5,6,3].
- Step 4: Element 6 is evaluated; since 6>5, it is automatically in the correct place →[1,2,4,5,6,3].
- Step 5: Element 3 is inserted before 4; elements 4,5,6 shift forward →[1,2,3,4,5,6].
- Example 3 (n=8):
- Initial Array: [4,3,2,10,12,1,5,6]
- Systematic insertion steps:
- Insert 3→[3,4,2,10,12,1,5,6]
- Insert 2→[2,3,4,10,12,1,5,6]
- Evaluate 10→ Remains in place →[2,3,4,10,12,1,5,6]
- Evaluate 12→ Remains in place →[2,3,4,10,12,1,5,6]
- Insert 1→ Shifts 12,10,4,3,2 right →[1,2,3,4,10,12,5,6]
- Insert 5→ Shifts 12,10 right →[1,2,3,4,5,10,12,6]
- Insert 6→ Shifts 12,10 right →[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.

- Partitioning Procedure (First Element as Pivot):
- Step 1: Initialize pointers: loc=0, left=0, and right=n−1.
- Step 2: Scan the array from right to left, comparing elements with the pivot value at loc.
- Step 3: If an element smaller than the pivot is encountered (A[right]<pivot), swap that element with the pivot and update the tracking pointer: loc=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]>pivot), swap that element with the pivot and update the tracking pointer: loc=left.
- Step 6: Repeat these alternating directional scans until the two scanning pointers converge (left=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.

- Alternative Partitioning Procedure (Two-Pointer Convergence / Hoare Variant):
- Set the first element as the pivot value.
- Advance the leftmark pointer to the right as long as elements are smaller than the pivot (A[leftmark]<pivot; stop when A[leftmark]>pivot).
- Retreat the rightmark pointer to the left as long as elements are larger than the pivot (A[rightmark]>pivot; stop when A[rightmark]<pivot).
- If leftmark<rightmark, exchange the values at leftmark and rightmark.
- When the pointers cross (rightmark<leftmark), swap the pivot with the value at rightmark. The position at rightmark becomes the split point.
- Complexity Analysis:
- Best-Case Time Complexity: O(nlog(n)) — Occurs when the chosen pivot consistently divides the sub-arrays into nearly equal halves, producing a balanced recursion tree of depth log2(n).
- Average-Case Time Complexity: O(nlog(n)) — Occurs under typical randomized distributions where partitions remain reasonably balanced.
- Worst-Case Time Complexity: O(n2) — Occurs when the pivot selection consistently produces maximally unbalanced partitions (e.g., partitioning an array of size n into sub-arrays of size 0 and n−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=9):
- Unsorted Array: A[9]=[51,95,66,72,42,38,39,41,15]
- Chosen Pivot Value: 51 (situated at index 0)
- Partitioning Steps:
- Initial state check: Element at index 1 (95) is >51; element at index 8 (15) is <51. Swap positions 1 and 8→[51,15,66,72,42,38,39,41,95].
- Subsequent check: Element at index 2 (66) is >51; element at index 7 (41) is <51. Swap positions 2 and 7→[51,15,41,72,42,38,39,66,95].
- Subsequent check: Element at index 3 (72) is >51; element at index 6 (39) is <51. Swap positions 3 and 6→[51,15,41,39,42,38,72,66,95].
- Center convergence check: Elements at index 4 (42) and index 5 (38) are both <51. Pointers cross and halt.
- Finalize split point: Swap pivot (51) with the value at the split point (38) →[38,15,41,39,42,51,72,66,95].
- Resulting Partitioned State:
- Left sub-array (<51): [38,15,41,39,42] (size 5)
- Correctly placed pivot: 51 at index 5
- Right sub-array (>51): [72,66,95] (size 3)
- Example 2 (n=9):
- Array: [54,26,93,17,77,31,44,55,20]
- Pivot Selected: 54
- Two-Pointer Convergence Process:
- Advance leftmark: 26<54 (advances); stops at 93>54.
- Advance rightmark: Stops immediately at 20<54.
- Exchange values at leftmark and rightmark (93 and 20) →[54,26,20,17,77,31,44,55,93].
- Advance leftmark past 17; stops at 77>54.
- Advance rightmark past 55; stops at 44<54.
- Exchange values at leftmark and rightmark (77 and 44) →[54,26,20,17,44,31,77,55,93].
- Advance leftmark; stops at 77>54.
- Advance rightmark; stops at 31<54.
- Pointers cross (rightmark<leftmark); split point confirmed at rightmark (holding 31).
- Exchange pivot (54) with 31→[31,26,20,17,44,54,77,55,93].
- Resulting Partitioned State: Pivot 54 is fixed in its final sorted position at index 5, flanked by a left sub-array of smaller values and a right sub-array of larger values.