DEV Community

Cover image for JavaScript Array sort() & Bubble Sort!
Sudhanshu Gaikwad
Sudhanshu Gaikwad

Posted on • Edited on

1

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

Enter fullscreen mode Exit fullscreen mode

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' ]

Enter fullscreen mode Exit fullscreen mode

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 ]

Enter fullscreen mode Exit fullscreen mode

Bubble Sort Implementation

Image description

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

Enter fullscreen mode Exit fullscreen mode

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.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay