View Single Post
Old Oct 28th, 2007, 7:39 AM   #8
lectricpharaoh
Caffeinated Neural Net
 
lectricpharaoh's Avatar
 
Join Date: Jun 2005
Location: Dry west coast of Canada
Posts: 928
Rep Power: 4 lectricpharaoh will become famous soon enough
Re: tasm sorting 5 integers with array

Re-read DaWei's post. Then try plotting out the logical flow before you write any further code. I'll give you an example using a bubble sort, since it's very easy to understand. It should look something like this:
set unsorted items = array size
while (unsorted items > 1)
  current item index = 0
  while (current item index < unsorted items)
    if (array[current item index] > array[current item index+1])
      swap (array[current item index], array[current item index+1])
    increment current item index
  decrement unsorted items
Here is the process translated to assembly (assumes all segment registers are correctly initialized):
sort:
  mov cx, [arraysize] ; load size of array
  cmp cx, 2           ; and ensure we have two or more elements
  jl  done            ; we're done if there are fewer than two elements
  mov bx, [array]     ; point at start of array- note 'array' is a pointer,
                      ; so we will dereference it in the inner loop below
nextpass:
  mov si, 0           ; SI is our current item index
nextelement:
  mov ax, [bx+si]     ; fetch current element
  cmp ax, [bx+si+1]   ; and compare to following element
  jge noswap          ; if the second is not smaller, skip the swap
  xchg ax, [bx+si+1]
  mov ax, [bx+si]
noswap:
  inc si              ; increment index for next element
  cmp cx, si          ; and check if we've finished the current pass
  jl nextelement      ; still on this pass, so process next element
  loop nextpass       ; do next pass if any remain, else we're done
done:
Be warned. First, it's been ages since I've played with assembly, so there may very well be errors. Second, I've used NASM syntax, but it's easy to translate to TASM syntax. Just remember that if it's in square brackets, it refers to a memory location, and if it's not, it's an assembly-time constant, ie an offset in TASM parlance (even labels are offsets, albeit into the code segment). I'll leave the rest (printing, etc) up to you; I'm not going to do everything for you.

As a final suggestion, I'd really advise you to comment your assembly code. It's not like a higher-level language where you can derive a lot of meaning from variable names and other constructs; poorly commented asm is damn near opaque when you come back to it later.
__________________
A man's knowledge is like an expanding sphere, the surface corresponding to the boundary between the known and the unknown. As the sphere grows, so does its surface; the more a man learns, the more he realizes how much he does not know. Hence, the most ignorant man thinks he knows it all. - L. Sprague de Camp
lectricpharaoh is online now   Reply With Quote