Sunday, January 9, 2011

Sort An Array Of numbers(Selection Sort)

Share Orkut
        print macro msg         lea dx,msg         mov ah,09h         int 21h     endm     read macro n,j1,j2     j1:mov ah,01h         int 21h         cmp al,0dh         je j2         sub al,30h         mov bl,al         mov ax,n         mov dx,0ah         mul dx         xor bh,bh         add ax,bx         mov n,ax         jmp j1     j2 :nop     endm     printmul macro n1,l2,l3         mov bx,000ah         mov ax,n1         xor cx,cx         ;push into stack     l2:xor dx,dx         div bx         push dx         inc cx         cmp ax,0000h         jne l2         ;pop from stack     l3:pop dx         add dl,30h         mov ah,02h         int 21h         loop l3     endm     .model small     .stack 100h     .data         msg1 db 10,13,'Enter a number: $'         msg2 db 10,13,' Sorted Array $'         msg3 db 10,13,' $'         msg4 db 10,13,'Enter the size of array: $'         msg5 db 10,13,' Orginal Array $'         n dw 0         num dw 100 dup(0)         sml dw 0     .code     main proc         mov ax,@data         mov ds,ax         print msg4         read n,jump1,jump2         ;read n elements         mov cx,n         mov si,00h     loop1:print msg1         ;read a multidigit number         read num[si],jump3,jump4         add si,02         loop loop1         ;printing unsorted array         print msg5         call display         ;Selection Sort         mov dx,n         dec dx         mov si,00h     loopout:mov cx,dx         mov di,si         ;assign 1st element as smallest         mov ax,num[di]         mov sml,ax         mov bx,di         ;compare smallest with other elements     loop2:add di,02         mov ax,num[di]         cmp sml,ax         jc notlarg         mov sml,ax         mov bx,di     notlarg:loop loop2         ;swap smallest and 1st element         mov ax,num[si]         mov di,bx         mov num[di],ax         mov bx,sml         mov num[si],bx         add si,02h         dec dx         jnz loopout         ;printing sorted array         print msg2         call display         mov ah,4ch         int 21h     main endp     display proc         mov cx,n         mov si,00h     l4: push cx         print msg3         printmul num[si],l5,l6         add si,02h         pop cx         loop l4         ret     display endp     end

No comments:

Post a Comment