Home  >  Article  >  Web Front-end  >  JavaScript Array sort() & Bubble Sort!

JavaScript Array sort() & Bubble Sort!

Patricia Arquette
Patricia ArquetteOriginal
2024-11-01 08:24:02264browse

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:

  • array: The array to be sorted.
  • compareFunction (Optional): A function that defines the sort order. If omitted, the array elements are sorted based on their string Unicode code points.

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

JavaScript Array sort() & Bubble Sort!

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!

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