Member-only story
Here are three common sorting algorithms implemented in JavaScript: Bubble Sort, Selection Sort, and Merge Sort. Each has its own use cases and efficiency, depending on the dataset and requirements.
1. Bubble Sort
Bubble Sort is one of the simplest sorting algorithms but is not the most efficient. It repeatedly steps through the list, compares adjacent elements, and swaps them if they’re in the wrong order. This process continues until no swaps are needed.
Time Complexity:
- Worst-case: O(n²)
- Best-case: O(n) (if the array is already sorted)
Code Example:
function bubbleSort(arr) {
let len = arr.length;
for (let i = 0; i < len; i++) {
for (let j = 0; j < len - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap if the current element is greater than the next
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
}
console.log(bubbleSort([5, 3, 8, 4, 2])); // Output: [2, 3, 4, 5, 8]
Use Case: Bubble Sort is useful for small or nearly sorted datasets. However, for larger datasets, more efficient sorting algorithms should be used.