SHARE
    TWEET
    ferrybig

    Javascript sorting with generators

    Mar 1st, 2021
    1,154
    0
    Never
    Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
    1. // HTML for this example: <pre id="output"></pre>
    2. function compare(a/*: number*/, b/*: number*/)/*: ['compare', number, number]*/ {
    3. return ['compare', a, b];
    4. }
    5. function swap(a/*: number*/, b/*: number*/)/*: ['swap', number, number]*/ {
    6. return ['swap', a, b];
    7. }
    8. function* bubbleSort(from/*: number*/, to/*: number*/)/*: Generator<['swap' | 'compare', number, number], void, number> */ {
    9. let swapped/*: boolean */;
    10. do {
    11. swapped = false;
    12. to -= 1; // decrement by 1 EACH loop, as we know the last element will be in place
    13. for (let j = from; j < to; j++) {
    14. if ((yield compare(j, j + 1)) > 0) {
    15. yield swap(j, j + 1);
    16. swapped = true;
    17. }
    18. }
    19. } while(swapped);
    20. }
    21. function log(text/*: string*/)/*: void */ {
    22. console.log(text);
    23. document.getElementById('output').innerText += text + '\n';
    24. }
    25. function test(array/*: number[] */)/*: void */ {
    26. const generator = bubbleSort(0, array.length);
    27. let latestArray = array;
    28. let nextValue = 0;
    29. while(true) {
    30. const action = generator.next(nextValue);
    31. if(action.done) {
    32. log(JSON.stringify(latestArray) + ': Done')
    33. return;
    34. } else if (action.value[0] === 'compare') {
    35. const a = latestArray[action.value[1]];
    36. const b = latestArray[action.value[2]];
    37. if(a > b) {
    38. nextValue = 1;
    39. } else if (a < b) {
    40. nextValue = -1;
    41. } else {
    42. nextValue = 0;
    43. }
    44. log(JSON.stringify(latestArray) + `: Compared ${action.value[1]}: ${a} to ${action.value[2]}: ${b} resulting in ${nextValue}`);
    45. } else if (action.value[0] === 'swap') {
    46. latestArray = [...latestArray]
    47. const tmp = latestArray[action.value[1]];
    48. latestArray[action.value[1]] = latestArray[action.value[2]];
    49. latestArray[action.value[2]] = tmp;
    50. log(JSON.stringify(latestArray) + `: Swapped index ${action.value[1]} and ${action.value[2]}`);
    51. } else {
    52. throw new Error('What? ' + JSON.stringify(action.value));
    53. }
    54. }
    55. }
    56. const array = [9, 3, 4, 0, 7, 5, 2, 8, 1, 6];
    57. test(array);
    Advertisement
    Add Comment
    Please, Sign In to add comment
    Public Pastes
    We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
    Not a member of Pastebin yet?
    Sign Up, it unlocks many cool features!

    AltStyle によって変換されたページ (->オリジナル) /