Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

Bubble Sort Javascript

/*A slightly better solution involves tracking a variable called "checked" 
which is initially set to FALSE and becomes true when there is a swap during the iteration. 
Running this code on a do while loop to run the sorting function only when "checked" is true 
ensures that the function will not run on a sorted array more than once.*/
[visualization](https://visualgo.net/en/sorting?slide=1);

let bubbleSort = (inputArr) => {
    let len = inputArr.length;
    let checked;
    do {
        checked = false;
        for (let i = 0; i < len; i++) {
            if (inputArr[i] > inputArr[i + 1]) {
                let tmp = inputArr[i];
                inputArr[i] = inputArr[i + 1];
                inputArr[i + 1] = tmp;
                checked = true;
            }
        }
    } while (checked);
    return inputArr;
};
Source by flexiple.com #
 
PREVIOUS NEXT
Tagged: #Bubble #Sort #Javascript
ADD COMMENT
Topic
Name
6+3 =