Member-only story
Famous Sorting Algorithms in JavaScript: Time and Space Complexity Explained
Sorting is a fundamental operation in computer science. Different sorting algorithms are designed to optimize performance based on the size and characteristics of the data. In this article, we’ll explore famous sorting algorithms, their implementations in JavaScript, and their time and space complexities. Importantly, we’ll avoid using built-in functions to give you a deeper understanding of the inner workings.
1. Bubble Sort
Bubble Sort repeatedly swaps adjacent elements if they are in the wrong order. It’s simple but inefficient for large datasets.
Code Implementation:
function bubbleSort(arr) {
let 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 elements
let temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
// Example usage
console.log(bubbleSort([64, 34, 25, 12, 22, 11, 90]));
Time and Space Complexity:
- Best Case (Already Sorted): O(n)
- Average Case: O(n²)
- Worst Case: O(n²)