"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Bubble Sorting, Insertion Sorting & Selection Sort Algorithm Using Javascript

Bubble Sorting, Insertion Sorting & Selection Sort Algorithm Using Javascript

Published on 2024-08-18
Browse:793

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[j 1]) {
            let temp = arr[j];
            arr[j] = arr[j 1];
            arr[j 1] = temp;
        }
    }
}

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

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[j]) {
            const temp = arr[j];
            arr[j] = arr[i];
            arr[i] = temp;
        }
    } 
}


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

Selection Sort

const arr = [5,4,3,2,1];
for (let i = 0; i 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]

Release Statement This article is reproduced at: https://dev.to/ashutoshsarangi/bubble-sorting-insertion-sorting-algorithm-using-javascript-8j1?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3