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 elements.
- Process:
- Record the start time using a system counter.
- Execute the sorting algorithm.
- Record the end time immediately after completion.
- Calculate the elapsed time (end time minus start time).
- Unit Conversion: Elapsed time is initially measured in nanoseconds (). To convert these to a more readable format, the value is divided by a million () to approximate milliseconds ().
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 " computer" in the block) versus a standard remote desktop connection.
- Bubble Sort Benchmark:
- On an array of items, performance varies.
- On an array of items, Bubble Sort took approximately to complete.
- Conclusion: Bubble Sort is inefficient for real-world data scales where exceeds , necessitating 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 or are reached (which are sorted by definition).
- Sub-arrays are then merged back together in sorted order.
Implementation of the
mergeMethod:- Signature:
public static int[] merge(int[] left, int[] right) - Internal Pointers:
l: Tracking the current index in theleftarray.r: Tracking the current index in therightarray.i: Tracking the current index in the resultingarray.
- Logic:
- Create a new result array with size .
- While both
leftandrightarrays have remaining elements, compareleft[l]andright[r]. - The smaller value is placed into
array[i], and the corresponding pointer (lorr) 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
whileloops.
- 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.
- Signature:
Implementation of the
mergeSortMethod:- Base Case: If
array.length <= 1, the array is returned as-is. - Splitting: The halfway point is calculated as .
- Array Fragmentation: The method
java.util.Arrays.copyOfRange(array, start, end)is used to create theleftandrightsub-arrays.left: Indices tohalf.right: Indiceshalftoarray.length.
- Recursion:
left = mergeSort(left)andright = mergeSort(right). - Merging: The final step is returning
merge(left, right).
- Base Case: If
Merge Sort Performance:
- In the demonstration, Merge Sort sorted the large array in approximately milliseconds (compared to Bubble Sort's 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
lowindex (the first element). - Pointers: A
leftpointer starts atlowand moving right; arightpointer starts athighmoving left. - Mechanism:
- Increment the
leftpointer whilearray[l] < pivot. - Decrement the
rightpointer whilearray[r] > pivot. - If the pointers have not crossed (), swap the values at those indices and move both pointers inward.
- Return the
rightpointer as the split point.
- Increment the
- Pivot Selection: In this basic implementation, the pivot is chosen as the element at the
Implementation of
quickSort:- Signature:
public static void quickSort(int[] array, int low, int high) - Recursive Steps:
- Check if
low < high. If not, return (base case). - Identify the splitting point via
pivotSort. - Recursively call
quickSortfor the left partition:(array, low, split). - Recursively call
quickSortfor the right partition:(array, split + 1, high).
- Check if
- Signature:
Performance and Risks:
- Quick Sort recorded a time of approximately 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 (). 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:
- Build Max Heap (Heapify): Transform the unsorted array into a Max Heap so the largest element is at the root (index ).
- 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 ).
- Repair Heap: Perform a "sift-down" (heapify) on the new root to restore the Max Heap property.
- Repeat: Repeat the swap and repair steps until the heap size is reduced to .
Complexity Analysis:
- Time Complexity: for best, average, and worst cases.
- Space Complexity: 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
mergefunction to step through the left and right arrays to fill the result array.
- Response: The lecturer briefly re-explains the pointer logic used in the
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 and size ). This leads to a recursion depth of , which exceeds the Java stack limit for large .