Comparison of Quick Sort, Merge Sort and Heap Sort

Data Structures and Algorithms Note

Allie Hsu
Coder Life
4 min readFeb 28, 2022

--

Quick Sort and Merge Sort are Divide and Conquer algorithm

Quick Sort

Step

  1. pick a pivot (in this example will always pick the last element as a pivot)
  2. do partition then return the pivot index
  3. do quick sort for array before the pivot
  4. do quick sort for array after the pivot

when all subarray finished with partition, the array sorted

Note: if (start < end) can prevent doing quick_sort when start and pivot both are 0 and end is 1-> quick_sort(array, start=0, (0-1)= -1) or quick_sort(array, (0+1)=1, end=1) , like array = [1,2]

How to implement partition

Find the item from the start index that value is greater than the pivot, it should be put on the right side, while finding the position from the end index that value is less than the pivot and it should be put on the left side. Swap these two items (left to right and right to left), but we need to set a condition before the swap, that is only if start index < end, otherwise the start index is already at the right side of the end index item, no need to swap.

When all the other items are put in the correct position, swap the pivot to the index start.

# set pivot as end value

# set pivot as start value

Time Complexity: O(n logn)
Space Complexity: O(n²)

Merge Sort

Step

  1. Find the middle point to divide the array into two halves:
    mid = len(arr)//2
  2. Call merge sort for left half:
    left_arr = arr[:mid]
    Call merge_sort(left_arr)
  3. Call merge sort for second half:
    right_arr = arr[mid:]
    Call merge_sort(right_arr)
  4. Merge the two halves sorted in step 2 and 3:
    Call merge(left_arr, right_arr)

Time Complexity: O(n logn)
Space Complexity: O(n)

Heap Sort

Heap sort is based on Binary Heap data structure. A Binary Heap is a Complete Binary Tree (every level, except the level of leaves, is completely filled, the children can be two or one at the leaf level, and all nodes are as far left as possible.

And it can be created as an array that has this feature:
If the parent node is stored at index I, the left child can be calculated by 2 * I + 1 and the right child by 2 * I + 2

Heapify

The process of reshaping a binary tree into a heap data structure. Heapify procedure must be performed in the bottom-up order when children nodes are heapified.

Heap sort function

Time Complexity: The time complexity of heapify is O(logn). The time complexity of heapSort() is O(n) and the overall time complexity of Heap Sort is O(n logn).

--

--

Allie Hsu
Coder Life

A tech enthusiast who is keen to develop new skills