DEV Community

Cover image for How do we sort an Array in Javascript without Sort function?
Imran Shaik
Imran Shaik

Posted on • Edited on

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

To sort and arrya 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]
consol.log("sorted Array ", bubbleSort(array));
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)