0

我试图将这两个排序的数组合并在一起。我知道问题是当程序在达到其大小限制后尝试比较第一个数组时,但我不知道如何克服这个问题。任何帮助将非常感激。

include irvine32.inc
Title ArrayMerge

.data
a1  dw 1,3,4,7,9,15,17
a2  dw 2,6,8,10,11,14,18,19
a3  dw 15 dup(0)

.code
main proc
    sub     EAX,EAX
    mov     ESI,OFFSET a1
    mov     EDI,OFFSET a2
    mov     EDX,OFFSET a3

    call    Merge
    call    Display
    exit
main endp

;=====================================================================
Merge proc
    mov     ECX,lengthof a3 ;Set loop times
TheLoop:
TheJump:
    mov     ax,[ESI]
    cmp     ax,[EDI]
    jl      AddA1  ;Jump if less
    jg      AddA2  ;Jump if greater
    Loop    TheLoop
    jmp     EndJump
AddA1:
    mov     ax,[ESI]
    mov     [EDX],ax
    add     ESI,2
    add     EDX,2
    jmp     TheJump

AddA2:
    mov     ax,[EDI]
    mov     [EDX],ax
    add     EDI,2
    add     EDX,2
    jmp     TheJump

EndJump:
    ret
Merge endp
;==================================================================
Display proc
    mov     ECX,lengthof a3 ;Set loop times
    mov     EDX,offset a3

DisplayLoop:
    mov     ax,[EDX]
    add     EDX,2
    call    writedec
    call    crlf
    loop    DisplayLoop
    ret
Display endp
;===================================================================
end main
4

1 回答 1

1

您应该为每个数组处理的元素数量维护单独的计数器。一旦到达其中任何一个的末尾,只需从另一个复制剩余的元素。另请注意,如果元素相等,则不要复制,但应该复制。

i = j = k = 0;
while(i < length1 && j < length2)
{
    switch(compare(src1[i], src2[j]))
    {
        case -1: // src1 is less, copy it
            dst[k++] = src1[i++];
            break;
        case 0:  // equal, copy src2 but also increment i
            i++;
            // fall-through
        case 1:  // src2 is less, copy it
            dst[k++] = src2[j++];
    }
}
// at this point we have reached the end of one of the arrays
// just copy remaining elements
// note only one of these loops will do anything
while(i < length1)
{
    dst[k++] = src1[i++];
}
while(j < length2)
{
    dst[k++] = src2[j++];
}
于 2012-12-11T01:54:05.147 回答