π Sorting
One-line summary: Rearrange elements in order β the prerequisite for binary search, two pointers, and many greedy algorithms.
Enhanced Visualizationβ
Interactive comparison of Bubble Sort, Quick Sort, and Merge Sort with real-time performance metrics
Algorithm Analysisβ
The enhanced animation above demonstrates three fundamental sorting paradigms:
π΄ Bubble Sort - Simple but Inefficientβ
- Strategy: Compare adjacent elements and swap if out of order
- Performance: ~500,000 operations for n=1000 elements
- Visual: Watch elements "bubble" to their correct positions
- Best for: Educational purposes, very small datasets
π£ Quick Sort - Efficient Divide-and-Conquerβ
- Strategy: Choose pivot, partition around it, recursively sort
- Performance: ~10,000 operations for n=1000 elements
- Visual: See pivot selection and partitioning phases
- Best for: General-purpose sorting, in-place requirements
π΅ Merge Sort - Stable and Predictableβ
- Strategy: Divide array, sort halves, merge sorted results
- Performance: ~10,000 operations for n=1000 elements
- Visual: Observe divide-and-conquer with merging phases
- Best for: Stable sorting, linked lists, external sorting
Complete Algorithm Comparisonβ
| Algorithm | Time (avg) | Time (worst) | Space | Stable? |
|---|---|---|---|---|
| Bubble Sort | O(nΒ²) | O(nΒ²) | O(1) | Yes |
| Selection Sort | O(nΒ²) | O(nΒ²) | O(1) | No |
| Insertion Sort | O(nΒ²) | O(nΒ²) | O(1) | Yes |
| Merge Sort | O(n log n) | O(n log n) | O(n) | Yes |
| Quick Sort | O(n log n) | O(nΒ²) | O(log n) | No |
| Heap Sort | O(n log n) | O(n log n) | O(1) | No |
| Counting Sort | O(n + k) | O(n + k) | O(k) | Yes |
| Radix Sort | O(nk) | O(nk) | O(n+k) | Yes |
Cyclic Sort: for arrays containing numbers in range [1..n] β place each number at index num-1 in O(n), O(1) space.
Common Patternsβ
Merge Sortβ
function mergeSort(arr) {
if (arr.length <= 1) return arr;
const mid = Math.floor(arr.length / 2);
return merge(mergeSort(arr.slice(0, mid)), mergeSort(arr.slice(mid)));
}
function merge(left, right) {
const result = [];
let i = 0, j = 0;
while (i < left.length && j < right.length)
result.push(left[i] <= right[j] ? left[i++] : right[j++]);
return result.concat(left.slice(i), right.slice(j));
}
Cyclic Sortβ
function cyclicSort(nums) {
let i = 0;
while (i < nums.length) {
const correct = nums[i] - 1;
if (nums[i] !== nums[correct]) [nums[i], nums[correct]] = [nums[correct], nums[i]];
else i++;
}
return nums;
}
Pitfallsβ
- Quick sort worst case O(nΒ²) on sorted input β use random pivot or 3-way partition
- Stable vs unstable: use stable sort when equal elements must maintain relative order
- JS
Array.sort()is not guaranteed stable in older engines (ES2019+ guarantees it)
Practice Problemsβ
Related Topicsβ
- Binary Search β requires sorted input
- Two Pointers β converging pointers need sorted array
- Heap β heapsort; partial sort for Top-K
β Back to Home Β· Β© sparshjaswal