Você está na página 1de 3

TITLE SHELL SORT IMPLEMENTATION (main.

asm)
; Author: Jeremias Tays
; Description: This program initializes an array with n random
; numbers and then sorts them using a shellsort

INCLUDE Irvine32.inc
INTEGER_COUNT = 4 ;Size of array
.data
array DWORD INTEGER_COUNT DUP(?)
str1 BYTE "Array before sort: ",0
str2 BYTE "Array after sort: ",0
temp DWORD ?
flag BYTE 1
d BYTE INTEGER_COUNT
len BYTE INTEGER_COUNT
.code
main PROC
mov ebx,OFFSET array
call InitializeArray
mov edx,OFFSET str1
call WriteString
call DisplayForwardArray
call ShellSort
mov edx,OFFSET str2
call WriteString
call DisplayForwardArray

exit
main ENDP
;------------------------------------------------
InitializeArray PROC USES ecx edx eax
;
;This function initializes the array with random
;integers using the Randomize function.
mov ecx,INTEGER_COUNT ;loop counter
;------------------------------------------------
call Randomize
L0: mov eax,10
call RandomRange
call WriteInt
call DumpRegs
mov [ebx],eax ;store in array
add ebx,TYPE array ;next integer
loop L0 ;repeat until ecx=0
ret
InitializeArray ENDP
;------------------------------------------------
DisplayForwardArray PROC USES ebx ecx eax
;
;This function displays the array in order.
;------------------------------------------------
mov esi,OFFSET array
mov ecx,INTEGER_COUNT ;loop counter
L1:
mov eax,[esi] ;address of array element
add esi,TYPE array ;next integer
call Crlf ;output next line
call WriteInt ;display array element
loop L1 ;repeat until ecx=0
call Crlf ;output next line
ret
DisplayForwardArray ENDP
;------------------------------------------------
ShellSort PROC USES ebx ecx eax
;
;This function sorts the array using a shell
;sort.
;------------------------------------------------
mov flag,1 ;set to 1 to enter while loop
mov d,INTEGER_COUNT ;d=number of elements in array
mov len,INTEGER_COUNT ;length of array
L0: cmp flag,1 ;does flag equal 1? Yes, jump L1
je L1
cmp d,1 ;is d greater than 1? No,jump L5
jle L5
L1: mov flag,0 ;Set swap flag to 0
add d,1 ;d+1 - d used for checking array element
distance
movsx ax,d ;divide d/2
mov bl,2
div bl
mov d,al ;d=(d+1)/2
movsx ecx,len ;loop counter
movsx ebx,d ;mov d into 32-bit reg
sub ecx,ebx ;sub ebx, from ecx
mov esi,0 ;set offset of array element to 0
mov edx,0 ;set offset of array element to compare
to 0
L2:
add ebx,esi ;set offset for array element to compare
to d
mov edx,array[ebx] ;mov array element to 32-bit reg
cmp array[esi],edx ;compare first element to d distance ele
ment
jle L3 ;is array[esi] less than equal?jump to L
3
xchg eax,edx ;swap elements
mov array[esi],eax
mov array[ebx],edx
mov flag,1 ;swap was made
L3:
add esi,TYPE array ;increment esi
loop L2 ;loop until ecx=0
jmp L0 ;re-enter while loop
L5:
;end while loop
ret
ShellSort ENDP

END main

Você também pode gostar