Logo

dev-resources.site

for different kinds of informations.

How do we sort an Array in Javascript without Sort function?

Published at
11/19/2024
Categories
javascript
arrays
angular
react
Author
Imran Shaik
Categories
4 categories in total
javascript
open
arrays
open
angular
open
react
open
How do we sort an Array in Javascript without Sort function?

Sorting an array without using the default JavaScript sort function.
There are multiple ways to sort an array in JavaScript. one of the most popular is Bubble Sort

Problem - you have an array of integers, sort the array
Sorting can either be Ascending or descending.

const array = [5,3,8,6,2]

To sort an array Without using the JavaScript sort function is bubble sort.

Bubble Sort
Bubble sort is one of the simplest sorting algorithm. It repeatedly step through the list of array and compares the adjacent elements, and swap them if they are in the wrong order otherwise No swap. This process continues until the list is in sorted order.

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]){
        let temp = arr[j];
        arr[j] = arr[j+1];
        arr[j+1] = temp;
    }
}
  }
 return arr;
}

let array = [5,3,8,6,2]
console.log("sorted Array ", bubbleSort(array));

Here's how Bubble Sort works: An illustrated explanation is provided below.

Pass 1:
Compare 5 and 3 → Swap → [3, 5, 8, 6, 2]
Compare 5 and 8 → No swap → [3, 5, 8, 6, 2]
Compare 8 and 6 → Swap → [3, 5, 6, 8, 2]
Compare 8 and 2 → Swap → [3, 5, 6, 2, 8]
Result after Pass 1: Largest element 8 is in its correct position.

Pass 2:
Compare 5 and 3 → No Swap → [3, 5, 6, 2, 8]
Compare 5 and 6 → No swap → [3, 5, 6, 2, 8]
Compare 6 and 2 → Swap → [3, 5, 2, 6, 8]
Compare 8 and 6 → No Swap → [3, 5, 2, 6, 8]
Result after Pass 2: Largest element 6, 8 is in its correct position.

In this way it will continue to swap the element until we get the sorted array i.e: [2, 3, 5, 6, 8]

Featured ones: