# Bubble sort, confused by flags

I did comparative analysis between one of the solutions from FCC and my own solution.

I am using while loop and trying to finish looping earlier using flags. Obviously, I broke something, because my solution doing more iterations for the same input, than one from FCC.

I wonder, where is my mistake. Maybe while loop is not good here at all?

Below my solution and FCC solution. I modified both solutions to show number of iterations in the function output.

Sidenote about something unexpected: apparently all this solutions can be used to pass the tests for the selection sort challenge. That would be cheating, obviously, I won’t exploit it)

FCC solution from guide

``````function bubbleSort(array) {
let iterations = 0
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length - 1 - i; j++) {
iterations++;
if (array[j] > array[j + 1])
[array[j], array[j + 1]] = [array[j + 1], array[j]]; // Using ES6 array destructuring to swap

}

}
return [array, iterations];
}

let test1 = [3, 2, 1, 4, 5];

console.log(bubbleSort(test1))//[ [ 1, 2, 3, 4, 5 ], 10 ]
``````

My solution:

``````function bubbleSort(array) {
// Only change code below this line
let iterations = 0;
let flag = false // flag used to quit loops if array is sorted already
while (!(flag)) {
flag = true;
//consider optimization via reducing term condition as in guide
for (let i = 0; i < array.length; i++) {
iterations++;
if (array[i] > array[i + 1]) {
flag = false
//alternative for swaps: ES6 destructuring or create a helper function
let temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
return [array, iterations];
// Only change code above this line
}

let test1 = [3, 2, 1, 4, 5];

console.log(bubbleSort(test1)); //[ [ 1, 2, 3, 4, 5 ], 15 ]
``````

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.