Im trying to merge these two sorted arrays together. I know the problem is when the program is trying to compare the first array after reaching its size limit, but I'm at a loss at figuring out how to get past this. Any help would be really appreciated.
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
You should maintain separate counters for how many elements you have processed from each array. Once you reach the end of either of them, just copy the remaining elements from the other. Also note if elements are equal you don't copy but you should.
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++];
}