Letβs sort this array using different algorithms π
```js id="arr01"
let nums = [40, 10, 50, 80];
---
## πΉ 1. Bubble Sort
Repeatedly swaps adjacent elements if they are in the wrong order.
```js id="bubble01"
let arr = [...nums];
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
let temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
console.log(arr);
β Simple but slow (O(nΒ²))
πΉ 2. Selection Sort
Finds the smallest element and places it at the correct position.
```js id="selection01"
let arr = [...nums];
for (let i = 0; i < arr.length - 1; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[i]) {
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
console.log(arr);
β
Fewer swaps than bubble sort
β οΈ Still O(nΒ²)
---
## πΉ 3. Insertion Sort
Builds the sorted array one element at a time.
```js id="insertion01"
let arr = [...nums];
for (let i = 1; i < arr.length; i++) {
let key = arr[i];
let j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
console.log(arr);
β
Efficient for small or nearly sorted arrays
β±οΈ O(nΒ²) worst case
πΉ 4. Merge Sort (Divide & Conquer)
Breaks the array into halves, sorts them, and merges back.
```js id="merge01"
function mergeSort(arr) {
if (arr.length <= 1) return arr;
let mid = Math.floor(arr.length / 2);
let left = mergeSort(arr.slice(0, mid));
let 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]);
i++;
} else {
result.push(right[j]);
j++;
}
}
return result.concat(left.slice(i)).concat(right.slice(j));
}
console.log(mergeSort(nums));
β
Much faster for large datasets
β±οΈ O(n log n)
π Uses extra space
---
## πΉ 5. Built-in Sort (JavaScript)
```js id="builtin01"
let arr = [...nums];
arr.sort((a, b) => a - b);
console.log(arr);
β Fast and optimized (recommended in real-world use)
π§ Final Output
All methods will return:
```js id="out01"
[10, 40, 50, 80]
---
## π‘ Key Takeaways
* Bubble, Selection, Insertion β Easy but slower (O(nΒ²))
* Merge Sort β Efficient (O(n log n)) for large arrays
* Built-in `.sort()` β Best for practical use
* Always understand the logic before memorizing code
Top comments (0)