-
-
Notifications
You must be signed in to change notification settings - Fork 21
Open
Description
Bubble-sort usually has a flag to indicate whether any elements were swapped during the last pass across the list - 'cos if no elements were swapped, the list is already in order and you can return. The implementation here doesn't have that, so if you bubble-sort a list that's already sorted, it still does O(n²) iterations.
The corrected implementation looks like this:
export const bubbleSort = function* (arr: number[]): SortingGenerator {
for (let i = 0; i < arr.length; i++) {
let sorted = true;
for (let j = 0; j < arr.length - i - 1; j++) {
yield { access: [j, j + 1], sound: j + 1 };
if (arr[j] > arr[j + 1]) {
sorted = false;
const temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
if (sorted) return;
}
};
Would you be interested in a PR with a fix for this?
Metadata
Metadata
Assignees
Labels
No labels