Back to DSA Topics
Sorting Algorithms
Learn various sorting algorithms and their time complexities.
Animated Visualization
Step 1 of 8
64
0
34
1
25
2
12
3
22
4
11
5
90
6
Bubble Sort: Unsorted array [64, 34, 25, 12, 22, 11, 90]
javascript
← Scroll →
// Bubble Sort - O(n²)function bubbleSort(arr) { const n = arr.length; for (let i = 0; i < n - 1; i++) { for (let j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { // Swap [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; } } } return arr;}// Quick Sort - O(n log n) averagefunction quickSort(arr) { if (arr.length <= 1) return arr; const pivot = arr[Math.floor(arr.length / 2)]; const left = arr.filter(x => x < pivot); const middle = arr.filter(x => x === pivot); const right = arr.filter(x => x > pivot); return [...quickSort(left), ...middle, ...quickSort(right)];}// Merge Sort - O(n log n)function mergeSort(arr) { if (arr.length <= 1) return arr; const mid = Math.floor(arr.length / 2); const left = mergeSort(arr.slice(0, mid)); const right = mergeSort(arr.slice(mid)); return merge(left, right);}function merge(left, right) { let result = []; let i = 0, j = 0; while (i < left.length && j < right.length) { if (left[i] < right[j]) { result.push(left[i++]); } else { result.push(right[j++]); } } return result.concat(left.slice(i)).concat(right.slice(j));}Swipe horizontally to view full code
Explanation
Sorting algorithms arrange elements in a particular order. Bubble Sort is simple but slow (O(n²)). Quick Sort and Merge Sort are more efficient (O(n log n)) and use divide-and-conquer strategy.
Operations & Complexity
Bubble SortO(n²)
Simple but slow
Quick SortO(n log n)
Efficient, uses pivot
Merge SortO(n log n)
Stable, divide and conquer
Heap SortO(n log n)
Uses heap data structure
Time Complexity
Bubble SortO(n²)
Simple but slow
Quick SortO(n log n)
Efficient, uses pivot
Merge SortO(n log n)
Stable, divide and conquer
Heap SortO(n log n)
Uses heap data structure