DEV Community

Abhishek Gupta
Abhishek Gupta

Posted on

πŸš€ Sorting Algorithms in JavaScript (Complete Guide with Examples)

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);
Enter fullscreen mode Exit fullscreen mode

βœ… 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);
Enter fullscreen mode Exit fullscreen mode

βœ… 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);
Enter fullscreen mode Exit fullscreen mode

βœ… 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


Enter fullscreen mode Exit fullscreen mode

Top comments (0)