|
| 1 | +/* |
| 2 | + * c128lib (c) 2023 |
| 3 | + * https://github.com/c128lib/framework |
| 4 | + */ |
| 5 | + |
| 6 | +#import "chipset/lib/vic2.asm" |
| 7 | + |
| 8 | +#importonce |
| 9 | +.filenamespace c128lib |
| 10 | + |
| 11 | +.namespace Sort { |
| 12 | +} |
| 13 | + |
| 14 | +/* |
| 15 | + Sort an array with bubble sort algorithm. |
| 16 | + Fast mode can be switched on/off while algorithm |
| 17 | + is running. Fast mode can also be enabled before |
| 18 | + macro is called. |
| 19 | + |
| 20 | + Params: |
| 21 | + arrayAddress - memory address of array |
| 22 | + arraySize - array size |
| 23 | + switchToFastModeWhileRunning - if true, fast mode |
| 24 | + will be enabled at start and disabled at end. |
| 25 | +*/ |
| 26 | +.macro BubbleSort(arrayAddress, arraySize, switchToFastModeWhileRunning) { |
| 27 | + .if (switchToFastModeWhileRunning == true) { |
| 28 | + lda #1 |
| 29 | + sta c128lib.Vic2.CLKRATE |
| 30 | + } |
| 31 | + |
| 32 | +start: |
| 33 | + ldx #arraySize |
| 34 | + |
| 35 | +sort_loop: |
| 36 | + ldy #0 |
| 37 | + |
| 38 | +inner_loop: |
| 39 | + lda arrayAddress, y |
| 40 | + cmp arrayAddress + 1, y |
| 41 | + bcc NoSwap |
| 42 | + pha |
| 43 | + lda arrayAddress + 1, y |
| 44 | + sta arrayAddress, y |
| 45 | + pla |
| 46 | + sta arrayAddress + 1, y |
| 47 | + |
| 48 | + NoSwap: |
| 49 | + iny |
| 50 | + cpy #arraySize - 1 |
| 51 | + bne inner_loop |
| 52 | + dex |
| 53 | + bne sort_loop |
| 54 | + |
| 55 | + .if (switchToFastModeWhileRunning == true) { |
| 56 | + dec c128lib.Vic2.CLKRATE |
| 57 | + } |
| 58 | +} |
| 59 | +.assert "BubbleSort($beef, 3, false)", { BubbleSort($beef, 3, false) }, |
| 60 | +{ |
| 61 | + ldx #3; ldy #0; lda $beef,y; cmp $bef0, y; bcc *+13; pha; |
| 62 | + lda $bef0, y; sta $beef, y; pla; sta $bef0, y; iny |
| 63 | + cpy #2; bne *-22; dex; bne *-27 |
| 64 | +} |
| 65 | +.assert "BubbleSort($beef, 3, true)", { BubbleSort($beef, 3, true) }, |
| 66 | +{ |
| 67 | + lda #1; sta $d030 |
| 68 | + ldx #3; ldy #0; lda $beef,y; cmp $bef0, y; bcc *+13; pha; |
| 69 | + lda $bef0, y; sta $beef, y; pla; sta $bef0, y; iny |
| 70 | + cpy #2; bne *-22; dex; bne *-27; |
| 71 | + dec $d030 |
| 72 | +} |
0 commit comments