Search code examples
assemblydosnasmswap

DOS Assembly - swapping values in bubblesort


I am trying to implement bubblesort in 16b dos assembly (I am using NASM). My program successfully generates table of 1024 random 16b numbers, now I have to sort them in descending order, I decided to use bubblesort, but my way of swapping them isn't working the way I think it should. Here is the code for swapping two numbers:

mov ax, [table+di]
cmp ax, [table+di+1]
jae dont_swap
mov bx, [table+di+1]
mov [table+di+1], ax
mov [table+di], bx

It is supposed to just swap a number that 'di' is pointing to with the next one in the table. It's hard for me to explain the effect so just look at some output the program gives:

-first few randomly generated numbers: 61923, 48369, 17084, 52802, 49358
-after sorting: 28482, 17007, 16962, 16962, 16962...

It just repeats the last number. Values after sorting aren't even in the original table. I am certain that the problem isn't outside the code I presented, because if I remove it, recompile the program it perfectly repeats the generated table.

EDIT Big thanks for everyone who contributed. The problem was not scaling offsets accordingly to variable's size. Table stores word variables while I iterated through bytes.


Solution

  • Since you're comparing and swapping words you need to scale your offsets accordingly. The next element will be 2 bytes after the current element, i.e. at [table+di+2].

    You haven't shown us how you're calculating/updating di, so don't forget that it also needs to be moved 2 bytes per element.