DEV Community

Ashutosh Sarangi
Ashutosh Sarangi

Posted on

3 1 1 1 1

Bubble Sorting, Insertion Sorting & Selection Sort Algorithm Using Javascript

Bubble Sort and Insertion Sort are 2 basic sorting algorithms are there. I implemented these algorithms using JavaScript.

Bubble Sort

const arr = [5,4,3,2,1];

for (let i = 0; i < arr.length; i++) {
    for (j = 0 ; j< arr.length-i; j++) {
        if (arr[j] > arr[j+1]) {
            let temp = arr[j];
            arr[j] = arr[j+1];
            arr[j+1] = temp;
        }
    }
}

console.log(arr); // [1,2,3,4,5]

Enter fullscreen mode Exit fullscreen mode

Insertion Sort

it is better than bubble sort + if you know the array is almost sorted it is best algorithm

const arr = [5,4,3,2,1];
for (let i = 0; i < arr.length; i++) {
    for (let j = i+1; j < arr.length; j++) {
        if (arr[i] > arr[j]) {
            const temp = arr[j];
            arr[j] = arr[i];
            arr[i] = temp;
        }
    } 
}


console.log(arr); // [1,2,3,4,5]

Enter fullscreen mode Exit fullscreen mode

Selection Sort

const arr = [5,4,3,2,1];
for (let i = 0; i< arr.length; i++) {
    let min = Infinity;
    let pos = -1;
    for(let j = i; j < arr.length; j++) {
        if (min > arr[j]) {
            min = arr[j];
            pos = j;
        }
    }

    const temp = arr[i];
    arr[i] = arr[pos];
    arr[pos] = temp;
}


console.log(arr); // [1,2,3,4,5]

Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

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

Okay