DEV Community

Detacht
Detacht

Posted on

Bubble Sort

V1- the second for loop has an -i as shown below

let bubbleSortV1 = (inputArr) => {
let len = inputArr.length;
for (let i = 0; i < len; i++) {
for (let j = 0; j < (len-1-i); j++) {
console.log("im in here with j v1 = "+ j);
if (inputArr[j] > inputArr[j + 1]) {
let tmp = inputArr[j];
inputArr[j] = inputArr[j + 1];
inputArr[j + 1] = tmp;
}
}
console.log("\n");
}
return inputArr;
};

The second version has no -i

let bubbleSortV2 = (inputArr) => {
let len = inputArr.length;
for (let i = 0; i < len; i++) {
for (let j = 0; j < (len-1); j++) {
console.log("im in here with j v2 = "+ j);
if (inputArr[j] > inputArr[j + 1]) {
let tmp = inputArr[j];
inputArr[j] = inputArr[j + 1];
inputArr[j + 1] = tmp;
}
}
console.log("\n");
}
return inputArr;
};

The results of these two versions are as shown below with an example for reference

Image description

Top comments (0)