汇编程序中的插入排序不排序

时间:2014-12-10 15:02:39

标签: sorting assembly insertion-sort

我试图按插入排序对数字数组进行排序,但它没有正确排序数字。我已经尝试了所有的东西,但它没有对它们进行排序。 如果你能帮助我找出问题的位置以及我如何解决它,我会很高兴谢谢!!

section .rodata
MSG:    DB  "welcome to sortMe, please sort me",10,0
S1: DB  "%d",10,0 ; 10 = '\n' , 0 = '\0'

section .data

array   DB 5,1,7,3,4,9,12,8,10,2,6,11   ; unsorted array
len DB 12   

section .text
align 16
global main
extern printf

main:
push MSG    ; print welcome message
call printf
add esp,4   ; clean the stack 

call printArray ;print the unsorted array

    push ebp        ;save old frame pointer
    mov ebp,esp     ;create new frame on stack
    pusha
    mov esi,array
    mov ecx,8
 OuterLoop:
    mov ebx,ecx
    InnerLoop:
            add esi,ebx ;basically makes array[0] to array[ebx]
            mov eax,[esi] ;eax=array[ebx]
            sub esi,8
            mov edx,[esi] ; edx=array[ebx-1]
            add esi,8
            cmp eax,edx ; if(eax<edx)
            jle skip2 ; skip the loop
            ;else:
            mov [esi],edx ;array[ebx]=array[ebx-1]
            sub esi,8
            mov [esi],eax ; array[ebx-1]=array[ebx]
            add esi,8
            sub esi,ebx ; return the array to its original state (array[0])
            sub ebx,8
            cmp ebx,0
            jne InnerLoop
    skip1:
    add ecx,8
    cmp ecx,96
    jle OuterLoop

    popa            ;restore registers
    mov esp,ebp     ;clean the stack frame
    pop ebp
    push MSG        ; print welcome message (to divide between the unsorted and sorted)
    call printf
    add esp,4       ; clean the stack
    call printArray        

    mov eax, 1      ;exit system call
    int 0x80


printArray:
push ebp    ;save old frame pointer
mov ebp,esp ;create new frame on stack
pusha       ;save registers

mov eax,0
mov ebx,0
mov edi,0

mov esi,0   ;array index
mov bl,byte[len]
add edi,ebx ; edi = array size

print_loop:
cmp esi,edi
je print_end
mov al ,byte[array+esi] ;set num to print in eax
push eax
push S1
call printf
add esp,8   ;clean the stack
inc esi
jmp  print_loop
print_end:
popa        ;restore registers
mov esp,ebp ;clean the stack frame
pop ebp     ;return to old stack frame
ret

skip2:
sub esi,ebx ; return the array to the original state
jmp skip1

1 个答案:

答案 0 :(得分:0)

你可以混合3种尺寸! 1.字节数组
2.双字的值
3. qwords的步骤

一旦您决定使用什么尺寸,请注意此代码。在它当前的qword形式中,它进行了额外的迭代! (使用jl OuterLoop

cmp ecx,96
jle OuterLoop

为什么不在这一行使用MOVZX到EAX?它更清洁。

mov al ,byte[array+esi] ;set num to print in eax

同样适用于

mov bl,byte[len]

mov esi,array放在OuterLoop:之后,你可以通过SKIP2来避免这种丑陋的迂回。