Implementation and Analysis of Merge Sort, Quick Sort, and Heap Sort

Benchmarking and Performance Metrics of Sorting Algorithms

  • Measuring Execution Time:

    • The lecturer demonstrates a method to benchmark algorithms by generating a random array containing 1000010000 elements.
    • Process:
      1. Record the start time using a system counter.
      2. Execute the sorting algorithm.
      3. Record the end time immediately after completion.
      4. Calculate the elapsed time (end time minus start time).
    • Unit Conversion: Elapsed time is initially measured in nanoseconds (1.0×10−9 s1.0 \times 10^{-9}\,s). To convert these to a more readable format, the value is divided by a million (10610^6) to approximate milliseconds (1.0×10−3 s1.0 \times 10^{-3}\,s).
  • Hardware and Environment Variables:

    • The execution speed varies significantly based on the hardware. The lecturer notes differences between a remote connection to a specific machine (the "21st21^{st} computer" in the block) versus a standard remote desktop connection.
    • Bubble Sort Benchmark:
      • On an array of 1000010000 items, performance varies.
      • On an array of 100000100000 items, Bubble Sort took approximately 13 s13\,s to complete.
      • Conclusion: Bubble Sort is inefficient for real-world data scales where N\text{N} exceeds 100000100000, necessitating O(nlog⁡n)\text{O}(n \log n) algorithms like Merge Sort or Quick Sort.

The Merge Sort Algorithm

  • Conceptual Overview:

    • Merge Sort uses the "Divide and Conquer" strategy. It is based on the observation that merging two already sorted lists into a single sorted list is computationally inexpensive.
    • The array is recursively split into smaller parts until sub-arrays of size 00 or 11 are reached (which are sorted by definition).
    • Sub-arrays are then merged back together in sorted order.
  • Implementation of the merge Method:

    • Signature: public static int[] merge(int[] left, int[] right)
    • Internal Pointers:
      • l: Tracking the current index in the left array.
      • r: Tracking the current index in the right array.
      • i: Tracking the current index in the resulting array.
    • Logic:
      • Create a new result array with size (left.length+right.length)(\text{left.length} + \text{right.length}).
      • While both left and right arrays have remaining elements, compare left[l] and right[r].
      • The smaller value is placed into array[i], and the corresponding pointer (l or r) is incremented.
      • Cleanup Phase: Once one array is exhausted, the remaining elements of the other array (which are already sorted) are copied directly into the result array using additional while loops.
    • Syntax Tip: The lecturer uses post-increment syntax (e.g., array[i++] = left[l++]) to keep the code compact, although caution is advised to avoid bugs.
  • Implementation of the mergeSort Method:

    • Base Case: If array.length <= 1, the array is returned as-is.
    • Splitting: The halfway point is calculated as half=array.length/2\text{half} = \text{array.length} / 2.
    • Array Fragmentation: The method java.util.Arrays.copyOfRange(array, start, end) is used to create the left and right sub-arrays.
      • left: Indices 00 to half.
      • right: Indices half to array.length.
    • Recursion: left = mergeSort(left) and right = mergeSort(right).
    • Merging: The final step is returning merge(left, right).
  • Merge Sort Performance:

    • In the demonstration, Merge Sort sorted the large array in approximately 1717 milliseconds (compared to Bubble Sort's 1300013000 milliseconds).

The Quick Sort Algorithm

  • Conceptual Overview:

    • Quick Sort is another Divide and Conquer algorithm but operates "in-place," meaning it requires significantly less auxiliary memory than Merge Sort.
    • It partitions the array around a "pivot" value. Elements smaller than the pivot move to the left, and elements larger move to the right.
  • The Partitioning Logic (pivotSort):

    • Pivot Selection: In this basic implementation, the pivot is chosen as the element at the low index (the first element).
    • Pointers: A left pointer starts at low and moving right; a right pointer starts at high moving left.
    • Mechanism:
      1. Increment the left pointer while array[l] < pivot.
      2. Decrement the right pointer while array[r] > pivot.
      3. If the pointers have not crossed (l<rl < r), swap the values at those indices and move both pointers inward.
      4. Return the right pointer as the split point.
  • Implementation of quickSort:

    • Signature: public static void quickSort(int[] array, int low, int high)
    • Recursive Steps:
      1. Check if low < high. If not, return (base case).
      2. Identify the splitting point via pivotSort.
      3. Recursively call quickSort for the left partition: (array, low, split).
      4. Recursively call quickSort for the right partition: (array, split + 1, high).
  • Performance and Risks:

    • Quick Sort recorded a time of approximately 1010 units, making it faster than Merge Sort in this instance.
    • The Worst Case: For an array that is already sorted, the recursive depth can become extreme (O(n2)O(n^2)). During the lecture, this caused a StackOverflowError, demonstrating that the algorithm is less robust than Merge Sort without optimized pivot selection (like median-of-three).

The Heap Sort Algorithm

  • Conceptual Overview:

    • Heap Sort leverages a Max Heap (a binary tree structure stored in an array where the parent is always greater than or equal to its children).
    • It is an in-place algorithm that does not rely on recursion, making it immune to stack overflow issues.
  • The Sorting Process:

    1. Build Max Heap (Heapify): Transform the unsorted array into a Max Heap so the largest element is at the root (index 00).
    2. Extract-and-Swap:
      • Swap the root element (the maximum) with the last element of the current heap.
      • Consider the last element to be "sorted" and remove it from the heap logic (decrease heap size by 11).
    3. Repair Heap: Perform a "sift-down" (heapify) on the new root to restore the Max Heap property.
    4. Repeat: Repeat the swap and repair steps until the heap size is reduced to 11.
  • Complexity Analysis:

    • Time Complexity: O(nlog⁡n)O(n \log n) for best, average, and worst cases.
    • Space Complexity: O(1)O(1) auxiliary space (in-place).

Questions & Discussion

  • Question (Visualizing Split/Merge): Do any students have questions about the splitting or joining process discussed in the previous session?

    • Response: The lecturer briefly re-explains the pointer logic used in the merge function to step through the left and right arrays to fill the result array.
  • Question (Recursive Context): Does calling the function return the sorted array or change it in place?

    • Response: Merge Sort, as implemented here, returns a new array (pass-by-value/return-by-value style). Quick Sort and Heap Sort modify the original array (in-place).
  • Question (Sorted Array Crash): Why did Quick Sort crash on the sorted array?

    • Response: Choosing the first element as the pivot in a sorted array results in the worst possible partitions (size 11 and size n−1n-1). This leads to a recursion depth of nn, which exceeds the Java stack limit for large N\text{N}.