Assembly - bubble sort for sorting string

馋奶兔 提交于 2019-11-27 16:10:43

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:

.MODEL small .STACK 1000h                        ; Don't skimp with stack!  .DATA     Struct0A EQU $                  ; Buffer for INT 21h/0Ah (max,got,buf)         max db 100                  ; Maximum characters buffer can hold (incl. CR (0Dh))         got db 0                    ; Number of characters actually read, (excl. CR (0Dh))         buf db 100 dup (0)          ; Actual characters read, including the final carriage return (0Dh)     Linefeed db 13, 10, '$'     GetString   db 'Enter string: $'  .CODE start:     mov ax, @DATA                           ; Initialize DS     mov ds, ax      ; Input String     mov ah, 09h     mov dx, OFFSET GetString     int 21h     mov dx, OFFSET Struct0A     mov ah, 0Ah     INT 21h      mov si, OFFSET buf                      ; Base for [si + bx]      xor bx, bx                              ; Prepare BX for following byte load     mov bl, got                             ; Load length of string = 0Dh at the end     mov BYTE PTR [si + bx], '$'             ; Delimiter for int 21h / 09h      outer:     dec bx                                  ; The last character is already at the right place     jz done                                 ; No characters left = done     mov cx, bx                              ; CX: loop variable     mov si, OFFSET buf     xor dl, dl                              ; DL (hasSwapped) = false      inner:     mov ax, [si]                            ; Load **two** characters     cmp al, ah                              ; AL: 1. char, AH: 2. char     jbe S1                                  ; AL <= AH - no change     mov dl, 1                               ; hasSwapped = true     xchg al, ah                             ; Swap characters     mov [si], ax                            ; Store swapped characters     S1:     inc si                                  ; Next pair of characters     loop inner      test dl, dl                             ; hasSwapped == true?     jnz outer                               ; yes: once more     done:      ; Print result     mov dx, OFFSET Linefeed     mov ah, 09h     int 21h     mov dx, OFFSET buf     mov ah, 09h     int 21h      mov ax, 4C00h     int 21h  END start 

And here is another "animated" illustration:

https://www.youtube.com/watch?v=lyZQPjUT5B4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!