Series
On this page

Common Sort Algorithms

We omit insertion sort, bubble sort and selection sort here.

Just remember that their time complexity is O(n2)O(n^2) in average and worst case.

Let’s start with merge sort and quick sort.

Merge Sort

Merge sort is a divide-and-conquer algorithm that divides the input array into two halves, recursively sorts each half, and then merges the sorted halves back together.

Actually what we want to do in sort algorithm is to delete the inversion pairs in the array. We can find the proof that at least O(nlog⁡n)O(n \log n) time is needed to sort an array by using the concept of inversion pairs.

Here is a simple implementation of merge sort in Java:

merge sort
import java.util.*;
public class Main{
static int N = 100010;
static int[] a = new int[N];
static int[] t = new int[N];
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i = 0;i<n;i++){
a[i] = sc.nextInt();
}
mergesort(0,n-1);
for(int i = 0;i<n;i++){
System.out.print(a[i]);
System.out.print(" ");
}
}
public static void mergesort(int l,int r){
if(l>=r){
return;
}
int mid = (l+r) >> 1;
mergesort(l,mid);
mergesort(mid+1,r);
int i = l;
int j = mid+1;
int k = 0;
while(i<=mid&&j<=r){
if(a[i]<=a[j]){
t[k++] = a[i++];
}else{
t[k++] = a[j++];
}
}
while(i<=mid){
t[k++] = a[i++];
}
while(j<=r){
t[k++] = a[j++];
}
for(i = l;i<=r;i++){
a[i] = t[i-l];
}
}
}

We can see this is a typical divide-and-conquer algorithm.

First we divide the array into two halves until we reach the base case where the subarray has one or zero elements (which are inherently sorted). Then we merge the sorted subarrays back together.

Its complexity is O(nlog⁡n)O(n \log n) in average and worst case.

Quick Sort

Quick sort is another divide-and-conquer algorithm that selects a ‘pivot’ element from the array and partitions the other elements into two sub-arrays according to whether they are less than or greater than the pivot. If the elments are larger than the pivot, they go to the right sub-array; if smaller, to the left sub-array.

The sub-arrays are then sorted recursively.

Here is a simple implementation of quick sort in Java:

quick sort
import java.util.*;
public class Main{
static int N = 100010;
static int[] a = new int[N];
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i = 0;i<n;i++){
a[i] = sc.nextInt();
}
quicksort(0,n-1);
for(int i = 0;i<n;i++){
System.out.print(a[i]);
System.out.print(" ");
}
}
public static void quicksort(int l,int r){
if(l>=r){
return;
}
int i = l-1;
int j = r+1;
int x = a[(l+r)>>1];
while(i<j){
while(a[++i]<x);
while(a[--j]>x);
if(i<j){
int t = a[j];
a[j] = a[i];
a[i] = t;
}
}
quicksort(l,j);
quicksort(j+1,r);
}
}

This is a really strong template for quick sort. Let’s analyze it step by step.

  1. Attention on line 23-24, where we select the pivot as the middle element of the array. Here we use the Hoare partition scheme to partition the array around the pivot.

So why do we use i = l - 1 and j = r + 1?

Because we want to use the ++i and omit the boundary check in the inner while loop.

  1. Why we don’t need = in while loop line 27-28?

Reason 1: Assume that all elements in the array are the same.

If we use <= or >=, the pointers i and j will meet at start or end index. This is not efficient.

Reason 2: Forced swap when i == j.

Seems that this will not affect the result, but it will make pivot stay at the middle postion.

  1. This is the most important part:
int x = a[(l + r) >> 1]; // choose pivot
// ...
quicksort(l, j); // left side
quicksort(j + 1, r); // right side

This has a strong rule:

If the recursive split is (l, j) and (j + 1, r), then Pivot absolutely cannot be selected as the right boundary a[r].

If the recursive split is (l, i - 1) and (i, r), then Pivot absolutely cannot be selected as the left boundary a[l].

Otherwise there will be dead loop.

This quick sort implementation has an average time complexity of O(nlog⁡n)O(n \log n), but in the worst case (which can occur when the smallest or largest element is always chosen as the pivot), its time complexity degrades to O(n2)O(n^2).

However, with good pivot selection strategies (like choosing the median or using randomization), quick sort can perform very efficiently in practice.

So this template is really worth memorizing.

Radix Sort

Radix Sort is actually not based on inversion pair. LSD (Least Significant Digit) is used by this algorithm. It exploits the concept of “positional notation” (digits):

Digit Splitting: It processes integers by individual digits (ones, tens, hundreds, etc.).

Bucketing: It prepares 10 buckets (numbered 0-9).

Multiple Rounds:

First, sort based on the 1’s digit (Least Significant Digit).

Then, sort based on the 10’s digit.

Continue until the highest digit is reached.

Stability: To ensure the order established in lower digits isn’t messed up when sorting higher digits, the sub-sorting algorithm used in each round must be stable. (We typically use Counting Sort for this).

import java.util.Arrays;
public class RadixSort {
// Utility function to get the maximum value in arr[]
// This is needed to know the number of digits/rounds required.
private static int getMax(int[] arr) {
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
// A function to do counting sort of arr[] according to
// the digit represented by exp (1, 10, 100...)
private static void countSort(int[] arr, int exp) {
int n = arr.length;
int[] output = new int[n]; // Output array that will have sorted numbers
int[] count = new int[10]; // Count buckets for digits 0-9
// 1. Store count of occurrences in count[]
// (arr[i] / exp) % 10 extracts the digit at the current position
for (int i = 0; i < n; i++) {
int digit = (arr[i] / exp) % 10;
count[digit]++;
}
// 2. Change count[i] so that count[i] now contains actual
// position of this digit in output[] (Prefix Sum)
for (int i = 1; i < 10; i++) {
count[i] += count[i - 1];
}
// 3. Build the output array (CRITICAL: Iterate from REAR to FRONT!)
// Traversing backwards ensures the algorithm is STABLE.
// Elements with the same digit preserve their original relative order.
for (int i = n - 1; i >= 0; i--) {
int digit = (arr[i] / exp) % 10;
output[count[digit] - 1] = arr[i];
count[digit]--;
}
// 4. Copy the output array to arr[], so that arr[] now
// contains sorted numbers according to current digit
for (int i = 0; i < n; i++) {
arr[i] = output[i];
}
}
// The main function to that sorts arr[] using Radix Sort
public static void radixSort(int[] arr) {
if (arr == null || arr.length == 0) {
return;
}
// 1. Find the maximum number to know number of digits
int max = getMax(arr);
// 2. Do counting sort for every digit. Note that instead
// of passing digit number, exp is passed. exp is 10^i
// (1, 10, 100, etc.)
for (int exp = 1; max / exp > 0; exp *= 10) {
countSort(arr, exp);
// Optional: Print array after each pass to see the progress
System.out.println("Sorting for exp=" + exp + ": " + Arrays.toString(arr));
}
}
// Main method for testing
public static void main(String[] args) {
int[] arr = {170, 45, 75, 90, 802, 24, 2, 66};
System.out.println("Original Array: " + Arrays.toString(arr));
radixSort(arr);
System.out.println("Sorted Array: " + Arrays.toString(arr));
}
}

Complexity AnalysisTime Complexity: O(d×(n+k))O(d \times (n + k))

nn: Number of elements in the array.

dd: Number of digits in the maximum number (e.g., 802 has 3 digits).

kk: The base/radix (here it is 10, for decimal numbers).

Since dd and kk are usually small constants, this is often considered linear time O(n)O(n), making it faster than QuickSort O(nlog⁡n)O(n \log n) for specific datasets.

Space Complexity: O(n+k)O(n + k)Requires an extra output array and count array.