DEV Community

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

Posted on • Edited on

4

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 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));
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.

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]

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs