sorting in js
#javascript
👤cs
📅Last updated 19 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.
💻Source Code
// 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);🔗Related Snippets
Similar code snippets you might find interesting
💬Comments (0)
🔒Please login to post comments
💬
No comments yet. Be the first to share your thoughts!
⚡Actions
Share this snippet:
👤About the Author
c
cs
Active contributor
