Sorting is not just about arranging elements.
It is about organizing data to enable faster searching, optimization, and decision-making.
In interviews, sorting problems test:
Bubble sort repeatedly compares adjacent elements and swaps them if they are in the wrong order.
Larger elements “bubble up” to the end.
for(int i = 0; i < n - 1; i++){
for(int j = 0; j < n - i - 1; j++){
if(arr[j] > arr[j + 1]){
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
Used mainly for teaching, rarely in production.
Find the smallest element and place it at the correct position.
for(int i = 0; i < n - 1; i++){
int minIndex = i;
for(int j = i + 1; j < n; j++){
if(arr[j] < arr[minIndex]){
minIndex = j;
}
}
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
Good when memory writes are expensive.
Insert each element into its correct position in the sorted part.
for(int i = 1; i < n; i++){
int key = arr[i];
int j = i - 1;
while(j >= 0 && arr[j] > key){
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
Used in:
Divide array into halves, sort each half, then merge.
void mergeSort(int[] arr, int l, int r){
if(l < r){
int mid = l + (r - l) / 2;
mergeSort(arr, l, mid);
mergeSort(arr, mid + 1, r);
merge(arr, l, mid, r);
}
}
Used in:
Choose a pivot, partition array, then sort subarrays.
int partition(int[] arr, int low, int high){
int pivot = arr[high];
int i = low - 1;
for(int j = low; j < high; j++){
if(arr[j] < pivot){
i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, high);
return i + 1;
}
Fastest in practice due to cache friendliness.
Uses a binary heap to sort elements.
void heapSort(int[] arr){
buildHeap(arr);
for(int i = n - 1; i > 0; i--){
swap(arr, 0, i);
heapify(arr, 0, i);
}
}
Used when worst-case guarantees are required.
Count frequency of each element.
int[] count = new int[max + 1];
for(int x : arr){
count[x]++;
}
Used when:
Sort numbers digit by digit.
Uses stable counting sort internally.
Used in:
Distribute elements into buckets, sort each bucket.
Used for:
A sorting algorithm is stable if equal elements retain their relative order.
Example:
(3,A) (3,B) → after sort → (3,A) (3,B)
Important when sorting objects by multiple keys.
In-place:
Out-of-place:
| Algorithm | Best | Average | Worst | Stable | Space |
|---|---|---|---|---|---|
| Bubble | O(n) | O(n²) | O(n²) | Yes | O(1) |
| Selection | O(n²) | O(n²) | O(n²) | No | O(1) |
| Insertion | O(n) | O(n²) | O(n²) | Yes | O(1) |
| Merge | O(n log n) | O(n log n) | O(n log n) | Yes | O(n) |
| Quick | O(n log n) | O(n log n) | O(n²) | No | O(log n) |
| Heap | O(n log n) | O(n log n) | O(n log n) | No | O(1) |