'Unsure if this implementation of insertion sort is correct?
I found this implementation of insertion sort that avoids using the typical while loop that I've seen across most video explanations. I'm not exactly sure if this is valid though. Wouldn't this be nearly identical to bubble sort? Would there really be any specific benefit of using this? Here are my implementations of insertion sort and bubble sort:
let arr = [1, 4, 6, 7, 8, 6, 3, 4, 5, 6, 6, 7];
const bubbleSort = (array) => {
for (let i = array.length; i > 0; i--) {
for (let j = 0; j < i; j++) {
if (array[j] > array[j + 1])
[array[j], array[j + 1]] = [array[j + 1], array[j]];
}
}
};
const insertSort = (array) => {
for (let i = 1; i < array.length; i++) {
for (let j = i; j > 0; j--) {
if (array[j] < array[j - 1])
[array[j - 1], array[j]] = [array[j], array[j - 1]];
}
}
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
