Sortscape

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 export function* bubbleSort( arr: number[], setArray: React.Dispatch<React.SetStateAction<number[]>>, setComparisonIndices: React.Dispatch<React.SetStateAction<comparisonIndices>> ): Generator<number[]> { const n = arr.length; for (let i = 0; i < n - 1; i++) { for (let j = 0; j < n - i - 1; j++) { setComparisonIndices({ indicies: [j, j + 1], }); if (arr[j] > arr[j + 1]) { setComparisonIndices({ indicies: [j], matchIndex: j + 1 }); yield []; [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; setArray([...arr]); // Update the array in state after every swap } yield []; } } return arr; // Signal that the algorithm is finished }