Abstract


  • Basically re-arranging a collection of items or data elements in an ascending or descending order

In-Place

Stability of Sorting

  • Stable if the items with the same value stay in the same order after sorting
  • Unstable if the items with the same value doesn’t stay in the same after sorting

Divide-and-Conquer Sorting

  • Divide: split array into two halves
  • Recursion up: hit the base case, kickstart sorting the two halves
  • Combine: merge the sorted halves

Bubble Sort


  • The idea here is that at each iteration , we are are going to ‘bubble up’ the biggest element in the range to the position. If no ‘bubbling’ happens in that particular iteration, it means the array is fully sorted and it is safe to terminate the sorting early
  • Bubble sort implementation in Java

Selection Sort


  • The idea here is that at each iteration , we are are going to select the smallest element in the range of the Array. Then swap it with element at the position
  • Selection sort implementation in java

Insertion Sort


  • The idea here is that at each iteration , we are are going to insert the element at the position to the prefix Array that is long, such that the new prefix array which is long remains sorted

Merge Sort


Handle large dataset well

The performance gains on large dataset with time complexity is huge.

And we can perform sorting on subset of the dataset at a time. For example, if our dataset is 10GB, and we need to load the data into the RAM to perform the sorting, but there is only 2GB RAM. With merge sort, we are able to load in 2GB at a time to perform sorting, and eventually sort the dataset.

Quick Sort


  • Divide: Select a ‘pivot’ element from the array
  • Partition: Rearrange the array so that all elements smaller than the pivot are placed to its left and all elements greater than the pivot are placed to its right.
  • Conquer: Recursively apply the same process (steps 1 and 2) to the sub-array on the left of the pivot and the sub-array on the right of the pivot. The base case for recursion occurs when an array or sub-array has one or zero elements, as they are already sorted by default

Important

Quick sort is an In-Place sorting algorithm.

How is partition implemented?

Essentially, we have two indices, i and j, both starting at index 0. The index i keeps track of the last position where an element smaller than the pivot was placed. Meanwhile, j scans the array from index 0 to the last index.

Here is a short video showing how partition is carried

References