Home >Web Front-end >JS Tutorial >How do we sort an Array in Javascript without Sort function?

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-29 22:49:10231browse

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

How Bubble sort works Details Illustration 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.

The above is the detailed content of How do we sort an Array in Javascript without Sort function?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn