So, I am trying to implement BubbleSort, using this code as template:
int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(arr[j-1] > arr[j]){
//swap elements
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
However, my assembly code only sorts the first 1 - 2 times and the produces an erroneous result. I tried running the debugger, stepping through multiple times, but my naive eyes could not spot any mistakes in the translation.
.data
arr DWORD 3,2,1,4,5
temp DWORD 0
arr_j DWORD 0
; Bubble Sort
.code
main proc
mov esi, OFFSET arr
mov eax, 0 ; for outer loop
mov ebx, 1 ; for inner loop
OuterLoop:
InnerLoop:
; swap elements
; referencing j in array
call MULTIPLY
add edx, esi ; edx = esi + 4*ebx that is *arr[j]
mov edi, [edx]
mov [arr_j], edi ; store arr[j]
sub edx, 4
mov edi, [edx] ; store arr[j - 1]
cmp edi, [arr_j] ; if(arr[j-1] > arr[j]) -> swap elements
jle FAIL_SWAP
; swap elements here
mov [temp], edi
mov edi, [arr_j]
mov ebp, [temp]
mov [edx], edi ; arr[j - 1] < arr[j]
add edx, 4
mov [edx], ebp
FAIL_SWAP:
inc ebx
mov ecx, LENGTHOF arr
sub ecx, eax
cmp ebx, ecx
jl InnerLoop
inc eax
cmp eax, LENGTHOF arr
jl OuterLoop
invoke ExitProcess,0
main ENDP
MULTIPLY PROC ; multiply 4 with ebx, store at edx
push esi
xor esi, esi
mov esi, 1
mov edx, ebx
LOOPER:
add edx, ebx
inc esi
cmp esi, 4
jl LOOPER
pop esi
ret
MULTIPLY ENDP
END main
Any help is really appreciated. Thanks.