I am writing a program in assembly using tasm. My task is to write a program that will use bubble sort to sort entered string alphabetically. Ex. if you enter "hello" it should write "ehllo". I have writened the begging to enter string and to sort it (I think it works okey until the end where it should print out the result, but at the end it just writes my .data once and the finisheds its work) P.S sorry for bad english
.model small
.stack 100h
.data
request db 'This program is using bubblesort to get alphabetical order of your enterd string', 0Dh, 0Ah, 'Enter your string:', 0Dh, 0Ah, '$'
result db 0Dh, 0Ah, 'Result:', 0Dh, 0Ah, '$'
buffer db 100, ?, 100 dup (0)
.code
start:
MOV ax, @data
MOV ds, ax
MOV ah, 09h
MOV dx, offset request
int 21h
MOV dx, offset buffer
MOV ah, 0Ah
INT 21h
MOV si, offset buffer
INC si
MOV bh, [si]
INC si
sort:
mov cx, [si]
mov bx, [si]
nextelement:
mov ax, [bx+si]
cmp ax, [bx+si+1]
jge noswap
xchg ax, [bx+si+1]
mov ax, [bx+si]
noswap:
inc si
cmp cx, si
jl nextelement
loop nextelement
MOV ah, 09h
MOV dx, offset result
int 21h
char:
LODSB
MOV ah, 2
MOV dl, al
INT 21h
DEC bh
JZ ending
JMP char
ending:
MOV ax, 4c00h
INT 21h
end start
1) For bubble sort you need two nested loops. The outer loop resets the start parameters for the inner loop until there is nothing left to swap.
2) You sort characters. That are 8-bit values (bytes). You can't load them directly into a 16-bit register (
mov ax, [bx+si]
).3)
[bx+si]
&[bx+si+1]
: this is so wrong that I cannot explain the error :-) .Instead of correcting your code I wrote an example "from scratch": following the illustration in http://en.wikipedia.org/wiki/Bubble_sort:
And here is another "animated" illustration:
https://www.youtube.com/watch?v=lyZQPjUT5B4