Revise All 5 Sorting Algorithms
đź’» Try it yourself first. Write your solution in Java, C++, Python or JavaScript and run it against hidden tests, right here.Revision notes
Sort an Array
Video: “Revise All 5 Sorting Algorithms” on LearnWithKiriti (Kodee). LeetCode 912.
Return the array sorted from smallest to largest (LeetCode 912). The revision page for bubble, selection, insertion, merge and quick sort.
Example: [5, 2, 3, 1] -> [1, 2, 3, 5]
| Folder | Sort | Time | Extra space |
|---|---|---|---|
1-BubbleSort/ |
Bubble: the biggest bubble rises to sortedEnd each pass; stop early if a pass made no swap. |
O(n²) worst, O(n) if already sorted | O(1) |
2-SelectionSort/ |
Selection: select the smallest of the rest and swap it into frontSlot. |
O(n²) | O(1) |
3-InsertionSort/ |
Insertion: make room for the newBook by shifting bigger books right, then drop it into the gap. |
O(n²) worst, O(n) if almost sorted | O(1) |
4-MergeSort/ |
Merge: split in half, sort each half, merge with two pointers (leftSpot, rightSpot). |
O(n log n) | O(n) |
5-QuickSort/ |
Quick: partition around the last number (pivot) with a wall, then sort each side. |
O(n log n) on average, O(n²) worst | O(log n) |
| Sort | Time (worst) | Best case | Extra space | Stable |
|---|---|---|---|---|
| Bubble | O(n²) | O(n) with early exit | O(1) | yes |
| Selection | O(n²) | O(n²) | O(1) | no |
| Insertion | O(n²) | O(n) | O(1) | yes |
| Merge | O(n log n) | O(n log n) | O(n) | yes |
| Quick | O(n²) | O(n log n) | O(log n) | no |
Rebuild it from the name
Rebuild each sort from its name. Bubble: neighbours swap, the biggest bubble rises to the end. Selection: select the smallest, put it at the front. Insertion: make room, then insert one more book. Merge: split, sort the halves, merge with two pointers. Quick: partition around a pivot, then sort each side. For a big array only merge sort (and quick sort on average) is O(n log n); the other three are O(n²).
Each folder has the same code as that sort’s own page, returning nums as LeetCode 912 asks. Every program sorts [5, 2, 3, 1] (the part under “Run it locally”); the solution itself is the same code as the practice panel’s Start menu on learnwithkiriti.com.
Bubble Sort
Bubble sort: shrink the end, stop early
After each pass the biggest bubble rises to sortedEnd, so the next pass stops one earlier; and if a pass made no swap, the array is sorted: stop.
for sortedEnd from size - 1 down to 1:
swapped = false
for currBubble from 0 to sortedEnd - 1:
nextBubble = currBubble + 1
if nums[currBubble] > nums[nextBubble]:
swap nums[currBubble] and nums[nextBubble]
swapped = true
if not swapped:
stop // already sorted
Dry run on [7, 2, 8, 1, 5] (the sort’s own example):
| sortedEnd | pass result | swapped? |
|---|---|---|
| 4 | [2, 7, 1, 5, 8] | yes |
| 3 | [2, 1, 5, 7, 8] | yes |
| 2 | [1, 2, 5, 7, 8] | yes |
| 1 | [1, 2, 5, 7, 8] | no -> stop |
Worst case (reversed input) still O(n²); best case (sorted) one pass, O(n). O(1) extra space. Stable: equal numbers never swap.
class Solution {
public int[] sortArray(int[] nums) {
// after each pass, the biggest bubble rises to sortedEnd
for (int sortedEnd = nums.length - 1; sortedEnd > 0; sortedEnd--) {
boolean swapped = false;
for (int currBubble = 0; currBubble < sortedEnd; currBubble++) {
int nextBubble = currBubble + 1;
if (nums[currBubble] > nums[nextBubble]) {
swap(nums, currBubble, nextBubble);
swapped = true;
}
}
// a pass with no swaps means the array is already sorted
if (!swapped) {
break;
}
}
return nums;
}
private void swap(int[] nums, int left, int right) {
int held = nums[left];
nums[left] = nums[right];
nums[right] = held;
}
}class Solution {
public:
vector<int> sortArray(vector<int>& nums) {
// after each pass, the biggest bubble rises to sortedEnd
for (int sortedEnd = nums.size() - 1; sortedEnd > 0; sortedEnd--) {
bool swapped = false;
for (int currBubble = 0; currBubble < sortedEnd; currBubble++) {
int nextBubble = currBubble + 1;
if (nums[currBubble] > nums[nextBubble]) {
swap(nums[currBubble], nums[nextBubble]);
swapped = true;
}
}
// a pass with no swaps means the array is already sorted
if (!swapped) {
break;
}
}
return nums;
}
};def sort_array(nums):
# after each pass, the biggest bubble rises to sorted_end
for sorted_end in range(len(nums) - 1, 0, -1):
swapped = False
for curr_bubble in range(sorted_end):
next_bubble = curr_bubble + 1
if nums[curr_bubble] > nums[next_bubble]:
nums[curr_bubble], nums[next_bubble] = nums[next_bubble], nums[curr_bubble]
swapped = True
# a pass with no swaps means the array is already sorted
if not swapped:
break
return numsfunction sortArray(nums) {
// after each pass, the biggest bubble rises to sortedEnd
for (let sortedEnd = nums.length - 1; sortedEnd > 0; sortedEnd--) {
let swapped = false;
for (let currBubble = 0; currBubble < sortedEnd; currBubble++) {
const nextBubble = currBubble + 1;
if (nums[currBubble] > nums[nextBubble]) {
[nums[currBubble], nums[nextBubble]] = [nums[nextBubble], nums[currBubble]];
swapped = true;
}
}
// a pass with no swaps means the array is already sorted
if (!swapped) {
break;
}
}
return nums;
}Selection Sort
Selection sort
For each frontSlot, check every candidate in the rest, remember the smallest (smallestSpot), and swap it into frontSlot. At most n - 1 swaps: the fewest moves of the simple sorts.
for frontSlot from 0 to size - 2:
smallestSpot = frontSlot
for candidate from frontSlot + 1 to size - 1:
if nums[candidate] < nums[smallestSpot]:
smallestSpot = candidate
if smallestSpot != frontSlot:
swap nums[frontSlot] and nums[smallestSpot]
Dry run on [7, 2, 8, 1, 5] (the sort’s own example):
| frontSlot | smallestSpot (value) | array after the swap |
|---|---|---|
| 0 | 3 (1) | [1, 2, 8, 7, 5] |
| 1 | 1 (2) | [1, 2, 8, 7, 5] (already in place, no swap) |
| 2 | 4 (5) | [1, 2, 5, 7, 8] |
| 3 | 3 (7) | [1, 2, 5, 7, 8] |
Always about n²/2 comparisons: O(n²), even on sorted input. At most n - 1 swaps. O(1) extra space. Not stable (a swap can jump over an equal number).
class Solution {
public int[] sortArray(int[] nums) {
// each pass selects the smallest of the rest and puts it at frontSlot
for (int frontSlot = 0; frontSlot < nums.length - 1; frontSlot++) {
int smallestSpot = frontSlot;
for (int candidate = frontSlot + 1; candidate < nums.length; candidate++) {
if (nums[candidate] < nums[smallestSpot]) {
smallestSpot = candidate;
}
}
if (smallestSpot != frontSlot) {
swap(nums, frontSlot, smallestSpot);
}
}
return nums;
}
private void swap(int[] nums, int left, int right) {
int held = nums[left];
nums[left] = nums[right];
nums[right] = held;
}
}class Solution {
public:
vector<int> sortArray(vector<int>& nums) {
// each pass selects the smallest of the rest and puts it at frontSlot
for (int frontSlot = 0; frontSlot < (int)nums.size() - 1; frontSlot++) {
int smallestSpot = frontSlot;
for (int candidate = frontSlot + 1; candidate < (int)nums.size(); candidate++) {
if (nums[candidate] < nums[smallestSpot]) {
smallestSpot = candidate;
}
}
if (smallestSpot != frontSlot) {
swap(nums[frontSlot], nums[smallestSpot]);
}
}
return nums;
}
};def sort_array(nums):
# each pass selects the smallest of the rest and puts it at front_slot
for front_slot in range(len(nums) - 1):
smallest_spot = front_slot
for candidate in range(front_slot + 1, len(nums)):
if nums[candidate] < nums[smallest_spot]:
smallest_spot = candidate
if smallest_spot != front_slot:
nums[front_slot], nums[smallest_spot] = nums[smallest_spot], nums[front_slot]
return numsfunction sortArray(nums) {
// each pass selects the smallest of the rest and puts it at frontSlot
for (let frontSlot = 0; frontSlot < nums.length - 1; frontSlot++) {
let smallestSpot = frontSlot;
for (let candidate = frontSlot + 1; candidate < nums.length; candidate++) {
if (nums[candidate] < nums[smallestSpot]) {
smallestSpot = candidate;
}
}
if (smallestSpot !== frontSlot) {
[nums[frontSlot], nums[smallestSpot]] = [nums[smallestSpot], nums[frontSlot]];
}
}
return nums;
}Insertion Sort
Insertion sort: make room, then insert
Take the newBook, shift every bigger book one step right to make room, then drop newBook into the gap. One write per step.
for newBookSpot from 1 to size - 1:
newBook = nums[newBookSpot]
gap = newBookSpot
while gap > 0 and nums[gap - 1] > newBook:
nums[gap] = nums[gap - 1] // shift right
gap = gap - 1
nums[gap] = newBook
Dry run on [7, 2, 8, 1, 5] (the sort’s own example):
Inserting 1 (newBookSpot = 3) into [2, 7, 8 | 1, 5]:
| gap | shift | array |
|---|---|---|
| 3 | 8 moves right | [2, 7, 8, 8, 5] |
| 2 | 7 moves right | [2, 7, 7, 8, 5] |
| 1 | 2 moves right | [2, 2, 7, 8, 5] |
| 0 | stop, write newBook | [1, 2, 7, 8, 5] |
O(n²) worst case (reversed), O(n) best case (already sorted), great for almost-sorted data. O(1) extra space. Stable.
class Solution {
public int[] sortArray(int[] nums) {
// everything left of newBookSpot is already sorted
for (int newBookSpot = 1; newBookSpot < nums.length; newBookSpot++) {
int newBook = nums[newBookSpot];
int gap = newBookSpot;
// shift every bigger book one step right to make room
while (gap > 0 && nums[gap - 1] > newBook) {
nums[gap] = nums[gap - 1];
gap--;
}
nums[gap] = newBook;
}
return nums;
}
}class Solution {
public:
vector<int> sortArray(vector<int>& nums) {
// everything left of newBookSpot is already sorted
for (int newBookSpot = 1; newBookSpot < (int)nums.size(); newBookSpot++) {
int newBook = nums[newBookSpot];
int gap = newBookSpot;
// shift every bigger book one step right to make room
while (gap > 0 && nums[gap - 1] > newBook) {
nums[gap] = nums[gap - 1];
gap--;
}
nums[gap] = newBook;
}
return nums;
}
};def sort_array(nums):
# everything left of new_book_spot is already sorted
for new_book_spot in range(1, len(nums)):
new_book = nums[new_book_spot]
gap = new_book_spot
# shift every bigger book one step right to make room
while gap > 0 and nums[gap - 1] > new_book:
nums[gap] = nums[gap - 1]
gap -= 1
nums[gap] = new_book
return numsfunction sortArray(nums) {
// everything left of newBookSpot is already sorted
for (let newBookSpot = 1; newBookSpot < nums.length; newBookSpot++) {
const newBook = nums[newBookSpot];
let gap = newBookSpot;
// shift every bigger book one step right to make room
while (gap > 0 && nums[gap - 1] > newBook) {
nums[gap] = nums[gap - 1];
gap--;
}
nums[gap] = newBook;
}
return nums;
}Merge Sort
Merge sort
Split in half until each piece has one number, then merge sorted halves with two pointers (leftSpot, rightSpot), always taking the smaller front number.
mergeSort(nums):
mergeSortHelper(nums, 0, n - 1)
mergeSortHelper(nums, low, high):
if low >= high: return # 0 or 1 item: already sorted
mid = low + (high - low) / 2 # never overflows, unlike (low + high) / 2
mergeSortHelper(nums, low, mid)
mergeSortHelper(nums, mid + 1, high)
merge(nums, low, mid, high)
merge(nums, low, mid, high):
merged = empty list
leftSpot = low, rightSpot = mid + 1
while leftSpot <= mid and rightSpot <= high: # both halves still have numbers
if nums[leftSpot] <= nums[rightSpot]: # <= keeps equal items in order (stable)
add nums[leftSpot] to merged; leftSpot++
else:
add nums[rightSpot] to merged; rightSpot++
add what is left of the left half, then of the right half (only one has leftovers)
copy merged back into nums starting at low
O(n log n) in the best, average and worst case: log n levels of halving, each merging all n numbers once. O(n) extra space (the merged list). Stable.
class Solution {
public int[] sortArray(int[] nums) {
mergeSortHelper(nums, 0, nums.length - 1);
return nums;
}
private void mergeSortHelper(int[] nums, int low, int high) {
// one number is already sorted
if (low >= high) {
return;
}
int mid = low + (high - low) / 2;
mergeSortHelper(nums, low, mid);
mergeSortHelper(nums, mid + 1, high);
merge(nums, low, mid, high);
}
private void merge(int[] nums, int low, int mid, int high) {
int[] merged = new int[high - low + 1];
int leftSpot = low;
int rightSpot = mid + 1;
int mergedSpot = 0;
// always take the smaller front number of the two sorted halves
while (leftSpot <= mid && rightSpot <= high) {
if (nums[leftSpot] <= nums[rightSpot]) {
merged[mergedSpot++] = nums[leftSpot++];
} else {
merged[mergedSpot++] = nums[rightSpot++];
}
}
while (leftSpot <= mid) {
merged[mergedSpot++] = nums[leftSpot++];
}
while (rightSpot <= high) {
merged[mergedSpot++] = nums[rightSpot++];
}
System.arraycopy(merged, 0, nums, low, merged.length);
}
}class Solution {
public:
vector<int> sortArray(vector<int>& nums) {
mergeSortHelper(nums, 0, (int)nums.size() - 1);
return nums;
}
private:
void mergeSortHelper(vector<int>& nums, int low, int high) {
// one number is already sorted
if (low >= high) {
return;
}
int mid = low + (high - low) / 2;
mergeSortHelper(nums, low, mid);
mergeSortHelper(nums, mid + 1, high);
merge(nums, low, mid, high);
}
void merge(vector<int>& nums, int low, int mid, int high) {
vector<int> merged;
int leftSpot = low;
int rightSpot = mid + 1;
// always take the smaller front number of the two sorted halves
while (leftSpot <= mid && rightSpot <= high) {
if (nums[leftSpot] <= nums[rightSpot]) {
merged.push_back(nums[leftSpot++]);
} else {
merged.push_back(nums[rightSpot++]);
}
}
while (leftSpot <= mid) {
merged.push_back(nums[leftSpot++]);
}
while (rightSpot <= high) {
merged.push_back(nums[rightSpot++]);
}
copy(merged.begin(), merged.end(), nums.begin() + low);
}
};def sort_array(nums):
merge_sort_helper(nums, 0, len(nums) - 1)
return nums
def merge_sort_helper(nums, low, high):
# one number is already sorted
if low >= high:
return
mid = (low + high) // 2
merge_sort_helper(nums, low, mid)
merge_sort_helper(nums, mid + 1, high)
merge(nums, low, mid, high)
def merge(nums, low, mid, high):
merged = []
left_spot = low
right_spot = mid + 1
# always take the smaller front number of the two sorted halves
while left_spot <= mid and right_spot <= high:
if nums[left_spot] <= nums[right_spot]:
merged.append(nums[left_spot])
left_spot += 1
else:
merged.append(nums[right_spot])
right_spot += 1
merged.extend(nums[left_spot:mid + 1])
merged.extend(nums[right_spot:high + 1])
nums[low:high + 1] = mergedfunction sortArray(nums) {
mergeSortHelper(nums, 0, nums.length - 1);
return nums;
}
function mergeSortHelper(nums, low, high) {
// one number is already sorted
if (low >= high) {
return;
}
const mid = Math.floor((low + high) / 2);
mergeSortHelper(nums, low, mid);
mergeSortHelper(nums, mid + 1, high);
merge(nums, low, mid, high);
}
function merge(nums, low, mid, high) {
const merged = [];
let leftSpot = low;
let rightSpot = mid + 1;
// always take the smaller front number of the two sorted halves
while (leftSpot <= mid && rightSpot <= high) {
if (nums[leftSpot] <= nums[rightSpot]) {
merged.push(nums[leftSpot++]);
} else {
merged.push(nums[rightSpot++]);
}
}
while (leftSpot <= mid) {
merged.push(nums[leftSpot++]);
}
while (rightSpot <= high) {
merged.push(nums[rightSpot++]);
}
for (let offset = 0; offset < merged.length; offset++) {
nums[low + offset] = merged[offset];
}
}Quick Sort
Quick sort (last number as pivot)
Partition around the last number (pivot): scan moves left to right, and everything ≤ pivot is swapped behind the wall. The pivot lands at the wall, then sort each side.
quickSortHelper(low, high):
if low >= high: return
pivotSpot = partition(low, high)
quickSortHelper(low, pivotSpot - 1)
quickSortHelper(pivotSpot + 1, high)
partition(low, high):
pivot = nums[high]
wall = low
for scan from low to high - 1:
if nums[scan] <= pivot:
swap nums[wall] and nums[scan]
wall = wall + 1
swap nums[wall] and nums[high]
return wall
Dry run on [7, 2, 8, 1, 5] (the sort’s own example):
partition([7, 2, 8, 1, 5]), pivot = 5:
| scan | value | <= 5? | wall after | array |
|---|---|---|---|---|
| 0 | 7 | no | 0 | [7, 2, 8, 1, 5] |
| 1 | 2 | yes | 1 | [2, 7, 8, 1, 5] |
| 2 | 8 | no | 1 | [2, 7, 8, 1, 5] |
| 3 | 1 | yes | 2 | [2, 1, 8, 7, 5] |
| end | pivot to wall | [2, 1, 5, 7, 8] |
5 is final; sort [2, 1] and [7, 8].
Average O(n log n); worst O(n²) when the pivot is always the smallest or biggest (sorted input with a last-number pivot). Extra space: the recursion, O(log n) on average. Not stable. A random pivot makes the worst case very unlikely.
class Solution {
public int[] sortArray(int[] nums) {
quickSortHelper(nums, 0, nums.length - 1);
return nums;
}
private void quickSortHelper(int[] nums, int low, int high) {
// one number is already sorted
if (low >= high) {
return;
}
int pivotSpot = partition(nums, low, high);
quickSortHelper(nums, low, pivotSpot - 1);
quickSortHelper(nums, pivotSpot + 1, high);
}
private int partition(int[] nums, int low, int high) {
int pivot = nums[high];
// everything left of wall is <= pivot
int wall = low;
for (int scan = low; scan < high; scan++) {
if (nums[scan] <= pivot) {
swap(nums, wall, scan);
wall++;
}
}
swap(nums, wall, high);
return wall;
}
private void swap(int[] nums, int left, int right) {
int held = nums[left];
nums[left] = nums[right];
nums[right] = held;
}
}class Solution {
public:
vector<int> sortArray(vector<int>& nums) {
quickSortHelper(nums, 0, (int)nums.size() - 1);
return nums;
}
private:
void quickSortHelper(vector<int>& nums, int low, int high) {
// one number is already sorted
if (low >= high) {
return;
}
int pivotSpot = partition(nums, low, high);
quickSortHelper(nums, low, pivotSpot - 1);
quickSortHelper(nums, pivotSpot + 1, high);
}
int partition(vector<int>& nums, int low, int high) {
int pivot = nums[high];
// everything left of wall is <= pivot
int wall = low;
for (int scan = low; scan < high; scan++) {
if (nums[scan] <= pivot) {
swap(nums[wall], nums[scan]);
wall++;
}
}
swap(nums[wall], nums[high]);
return wall;
}
};def sort_array(nums):
quick_sort_helper(nums, 0, len(nums) - 1)
return nums
def quick_sort_helper(nums, low, high):
# one number is already sorted
if low >= high:
return
pivot_spot = partition(nums, low, high)
quick_sort_helper(nums, low, pivot_spot - 1)
quick_sort_helper(nums, pivot_spot + 1, high)
def partition(nums, low, high):
pivot = nums[high]
# everything left of wall is <= pivot
wall = low
for scan in range(low, high):
if nums[scan] <= pivot:
nums[wall], nums[scan] = nums[scan], nums[wall]
wall += 1
nums[wall], nums[high] = nums[high], nums[wall]
return wallfunction sortArray(nums) {
quickSortHelper(nums, 0, nums.length - 1);
return nums;
}
function quickSortHelper(nums, low, high) {
// one number is already sorted
if (low >= high) {
return;
}
const pivotSpot = partition(nums, low, high);
quickSortHelper(nums, low, pivotSpot - 1);
quickSortHelper(nums, pivotSpot + 1, high);
}
function partition(nums, low, high) {
const pivot = nums[high];
// everything left of wall is <= pivot
let wall = low;
for (let scan = low; scan < high; scan++) {
if (nums[scan] <= pivot) {
[nums[wall], nums[scan]] = [nums[scan], nums[wall]];
wall++;
}
}
[nums[wall], nums[high]] = [nums[high], nums[wall]];
return wall;
}