Home > Article > Web Front-end > JavaScript Array sort() & Bubble Sort!
The JavaScript sort() method arranges array elements alphabetically by default, treating them as strings. A custom comparison function is needed for numerical sorting, allowing you to control the sorting criteria for precise and efficient organization.
Syntax:
arr.sort(compareFunction);
Parameters:
Example 1: Sorting an Array of Strings
// Original array let arr = ["Ganesh", "Ajay", "Kunal"]; console.log(arr); // Output:["Ganesh", "Ajay", "Kunal"] // Sorting the array console.log(arr.sort()); // Output: [ 'Ajay', 'Ganesh', 'Kunal' ]
Example 2: Sorting an Array of Numbers
// Original array let numbers = [40, 30, 12, 25]; console.log(numbers); // Output: [40, 30, 12, 25] // Sorting the array numbers.sort((a, b) => a - b); console.log(numbers); // Output: [ 12, 25, 30, 40 ]
Bubble Sort Implementation
In addition to using the built-in sort() method, you can implement your own sorting algorithm. Here’s an example using the Bubble Sort algorithm:
index.js
function Sortarr() { let Data = [40, 30, 12, 25]; for (let i = 0; i < Data.length; i++) { for (let j = 0; j < Data.length - 1; j++) { if (Data[j] > Data[j + 1]) { let temp = Data[j]; Data[j] = Data[j + 1]; Data[j + 1] = temp; } } } console.log(Data); // Output: [ 12, 25, 30, 40 ] } Sortarr();
This Bubble Sort implementation demonstrates a basic sorting technique that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.
The above is the detailed content of JavaScript Array sort() & Bubble Sort!. For more information, please follow other related articles on the PHP Chinese website!