2017-04-08 50 views
0

我必須鍵入和數組(只能用數字),並且當引入它時,它必須在第二個中排序。我所要做的就是實施必須對它們進行排序的PROC。我的問題是,我不知道如何,因爲我所取得的唯一成果是將第一個複製到第二個。感謝您的幫助,並對我的英語感到抱歉。用emu8086對數組進行排序(彙編)

;mov ax, vector[si] 
;mov vector[di], ax 
;this loop copy all elements 
; start code 
Sort_DecreasingOrder: 

cmp si, 0 
mov ax, vector1[si] 

bCompare: 
xor di, di 
mov bx, vector2[di] 
cmp ax, bx 
jge IntroduceBefore 
+1

例子e對於「泡泡」排序是[here](http://stackoverflow.com/a/26324630/3512216)。 – rkhb

回答

1

有排序的另一種方式知道作爲Selection Sort和這裏其:

數據段被定義爲:

elements db 7,1,0,5,'$' 
size dw $-elements - 1  ; size stores 5 (including '$') so we subtract one now it stores 4 (which is the actual number of elements) 
msg db 10,13,'Unsorted Array: $'   
msg2 db 10,13,'Sorted Array: $' 

過程進行排序的數組:

sort proc  

    mov cx, size  
    mov si, 0 
    mov di, 0 
    mov ax, 1 ; this is done 
    dec cx ; to avoid the last comparison 

    outerLoop:   

     push cx ; store the limit of outerLoop in stack 

     mov bl, elements[si] ; store the element in bl pointed by si             

     mov cx, size ; store the value of size in cx for innerLoop   
     sub cx, ax  ; this is done so that the limit does not proceed the limit of array elements. 

     innerLoop: 

      inc di     

      cmp bl, elements[di] ; compare the if BL is not greater than 
      jna continue   ; content of element pointed by DI if yes then continue otherwise swap the value by executing below statements 

      mov dl, elements[di] ; get the element pointed by DI into DL 
      mov elements[di], bl ; swap the 
      mov elements[si], dl ; elements 
      mov bl, dl    ; store the smallest element in BL        

      continue: 

     loop inner 

     inc ax               

     pop cx ; get the limit of outerLoop 

     inc si ; increment the index of outerLoop to point to the next element 

     mov di, si 

     loop outer       

    return2:  

     ret  

sort endp     

end  
+1

每當您找到新的候選元素時,都會進行大量交換。這幾乎沒有SelectionSort了。只要記錄你發現元素的位置並在最後以最大值交換。另外,使用[atomic'xchg'(即帶有內存操作數的xchg)](http://felixcloutier.com/x86/XCHG.html)會使得* *比需要的慢得多。另外,'jna continue'會比'ja' /'jmp'更有意義。或者更好的是,優化比較的分支結構是錯誤的並且不需要交換。 –

+1

你不需要CPU用'xchg dl,bl'交換寄存器,只需存儲相反的寄存器即可。另外,你已經有'bl' ='elements [si]',所以你不需要再加載它。 (但是,你將需要一個'mov bl,dl'指令我猜) –

+0

@Peter Cordes當我寫代碼時沒有時間進行優化,我有點慌張。我仍然很匆忙,因爲我必須準備後天的考試。 – Ahtisham