Here are 2 bubble sort algorithms:
1:
function bubbleSort(array) {
let i = 0;
let startVal = array[i];
let comparingVal = array[i + 1];
let iterations = array.length;
while (iterations > 0) {
if (comparingVal === undefined) {
i = 0;
startVal = array[i]
comparingVal = array[i + 1]
iterations--;
} else if (startVal > comparingVal) {
array[i] = comparingVal;
array[i + 1] = startVal;
startVal = array[i + 1];
comparingVal = array[i + 2];
i++;
} else {
startVal = array[i + 1];
comparingVal = array[i + 2];
i++;
}
}
return array;
}
2:
function bubbleSortTwo(array) {
const length = array.length;
for (let i = 0; i < length; i++) {
for (let j = 0; j < length; j++) {
if (array[j] > array[j + 1]) {
//swap
let temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
return array;
}
when tested in the browser using performance.now() Web API bubbleSortTwo yielded faster performance time even though there is a nested loop O(n^2) whereas bubbleSort only has one loop for which I would assume a time complexity of O(n). Why is this? Or am I missing something somewhere? (I am new to ds and algs so excuse my ignorance I am trying to learn)
n^2as you compare each ofnitems against allnitems. The performance difference is due to the code path of the second being simpler than the other. \$\endgroup\$nitems against allnitems um - only if the input is in reverse order. In an ordered array every item is compared to its neighbours, only. Time and again…) \$\endgroup\$whileloop. For 100 items it counts 100 * 100 iterations. \$\endgroup\$