How should I write a single code for both byte and word sized array? The code below doesn't terminate for one array being byte sized and the other one being word sized
In this code bubble sort algorithm is used to sort 2 arrays named as data and data2 but when I run the code it doesn't terminate and keeps on running.Am I writing the code correctly or there should be changes?
[org 0x0100]
jmp start
data: dw 60,40,50,22,5
data2: db 3,4,1,9,6
swapflag: db 0
swap:
mov ax, [bx si]
xchg ax, [bx si 2]
mov [bx si], ax
ret
bubblesort:
dec cx
shl cx, 1
mainloop:
mov si, 0
mov byte [swapflag], 0
innerloop:
mov ax, [bx si]
cmp ax, [bx si 2]
jbe noswap
call swap
mov byte [swapflag], 1
noswap:
add si, 2
cmp si, cx
jne innerloop
cmp byte [swapflag], 1
je mainloop
ret
start:
mov bx, data
mov cx, 10
call bubblesort
mov bx, data2
mov cx, 20
call bubblesort
mov ax, 0x4c00
int 0x21
CodePudding user response:
mov bx, data mov cx, 10 <<< 5 elements !!! call bubblesort mov bx, data2 mov cx, 20 <<< 5 elements !!! call bubblesort
You are calling the bubblesort subroutine with counts that are much too high for the 5-element arrays that you have. This error will process garbage data but does not explain why "it doesn't terminate".
The endless loop problem exists because, at the conclusion of the innerloop, you forget to lower the limit that is held in the CX register. It is by lowering the limit that we indicate that the last element is in its final place, and that we no longer need to consider it, thus reducing the task and working towards an end.
Next is a corrected version of the code. I did not optimize it so you can still recognize the problem and how it was solved.
; IN (bx,cx)
bubblesort16:
dec cx
shl cx, 1 *
mainloop:
mov si, 0
mov byte [swapflag], 0
innerloop:
mov ax, [bx si] *
cmp ax, [bx si 2] *
jbe noswap
swap: ;
xchg ax, [bx si 2] * ; better have this inlined
mov [bx si], ax * ;
mov byte [swapflag], 1
noswap:
add si, 2 *
cmp si, cx
jne innerloop
cmp byte [swapflag], 0 ;
je done ;
sub cx, 2 * ; new (solution)
jnz mainloop ;
done: ;
ret
How should I write a single code for both byte and word sized array?
The bubblesort sorting method is already the slowest method you can use, so why not make it worse?
I've marked with an asterisk the lines that change for the byte-sized version. Since they lie so scattered, the exercise of merging both sizes becomes futile.
Just call separate versions bubblesort16 and bubblesort8.
CodePudding user response:
I think that you should write the whole code for byte and then when you will also use word array, the byte subroutine should work for it.