sorting in js

By : cs

Language: javascript

Date Published: 2 weeks, 4 days ago

Sorting means arranging elements in ascending or descending order.
We’ll implement a classic algorithm — Bubble Sort — for simplicity and understanding.

Idea: Repeatedly swap adjacent elements if they are in the wrong order.
Time Complexity: O(n²)
Best For: Small datasets or learning basic sorting logic.

Style : Dark Mode : Line Number: Download Font Size:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Bubble Sort Implementation in JavaScript

/**
* Sorts an array in ascending order using Bubble Sort
* @param {number[]} arr - The array to sort
* @returns {number[]} - Sorted array
*/
function bubbleSort(arr) {
 let n = arr.length;

 // Outer loop for each pass
 for (let i = 0; i < n - 1; i++) {
   // Inner loop for pairwise comparisons
   for (let j = 0; j < n - i - 1; j++) {
     // Swap if elements are out of order
     if (arr[j] > arr[j + 1]) {
       let temp = arr[j];
       arr[j] = arr[j + 1];
       arr[j + 1] = temp;
     }
   }
 }

 return arr; // Return the sorted array
}

// Example usage:
const numbers = [64, 34, 25, 12, 22, 11, 90];
console.log("Original Array:", numbers);
const sortedArray = bubbleSort(numbers);
console.log("Sorted Array:", sortedArray);
javascript
Login to see the comments