Search code examples
loopsvisual-c++assemblymasmirvine32

Bubble sort issue in asm using vc++


This program just runs fine, but output is not correct

 INCLUDE Irvine32.inc

 .data
 array BYTE 5,4,3,2,1
 .code
 main PROC
 mov ecx,lengthof array

 l1:
 mov esi,0
 mov eax,0
 l2:
 mov al,array[esi]
 cmp al,array[esi+1]
 jbe noswap

 mov dl,array[esi+1]
 mov array[esi+1],al
 mov array[esi],dl

 noswap:
 add esi,1
 cmp esi,ecx
 jne l2

 loop l1

 mov esi,0
 mov esi,offset array
 mov ecx,lengthof array
 mov ebx,type array 
 call dumpmem

exit
main ENDP
END main

It gives the following output: 00 01 02 03 04

It is not showing 5 at the end. I think there is a problem in looping


Solution

  • In your code, ecx will start out at lengthof array (which is 5), and will go down to 1 (the loop instruction won't jump back to l1 when ecx becomes 0). This leads to problems in the inner loop: the first is that esi will never become 0, so you'll never be comparing the elements at positions 0 and 1; the other is that you'll be comparing the elements at positions 4 and 5 during the first iteration of l1. The array only has 5 elements, so position 5 is past the end of the array, since the positions are zero-based.

    You should instead initialize ecx to (lengthof array)-1. If MASM doesn't like that syntax, use lengthof array and put a dec ecx on the next line.
    And the loop l1 line should be changed to dec ecx followed by jns l1. That way ecx will go from 4..0, instead of from 5..1.