Half ascending and half descending code in 8051

8051 code to arrange the given numbers in half ascending and half descending order.


In this article let's see how to arrange a given array in half ascending and half descending. I think it's weird to hear the word half ascending and half descending but it is interesting as well.

Algorithm:

1) Store the length of array in r5 and the memory address in r0.
2)Obtaining the half of length and store it in r3,r4,r6 because making r3 as outer counter and r6 as inner counter.
3)Compare the two numbers of an array and if the first number is lesser than second number jump to last label.
4)If the first number is greater than second number then swap the numbers stored in memory location.
5)Decrement inner counter and repeat the above 3rd and 4th step for successive numbers.
6)Decrement outer counter and repeat the above 3rd,4th and 5th steps.
7)For next half of the array repeat the same steps but check the numbers to be in descending order.

Code goes here:


org 0000h
ljmp main
org 040h
main:
      mov r5,#10      ; length of array
      mov a,r5
      mov b,#2
      div ab          ; Obtaining the half of length of array
      mov r3,a
      mov r4,a
      mov r6,a
up1:  mov r0,#40h     ;Moving the memory address of array
      mov a,r4
      dec a
      mov r6,a
      mov b,@r0
      inc r0
      mov a,@r0
      cjne a,b,chkasc ;Comparing which is greater 
      ljmp last
up:   mov b,@r0       ;Comparing the next two numbers
      inc r0
      mov a,@r0
      cjne a,b,chkasc
      ljmp last
chkasc:jnc last       ;If the two numbers are in ascending order
       dec r0         ;swaping the numbers if they are greater
       mov @r0,a
       inc r0
       mov @r0,b
last:  djnz r6,up     ;Comparing the inner counter
       djnz r3,up1    ;comparing the outer counter
       mov a,r5
       subb a,r4
       mov r3,a
       mov r4,a
       mov r6,a
       add a,#40h     ;Obtaining the address of half of array
       mov r5,a
up3:   mov a,r5
       mov r0,a 
       mov a,r4
       dec a
       mov r6,a
       mov b,@r0
       inc r0
       mov a,@r0
       cjne a,b,chk1   ;checking first two numbers to arrange in descending order
       ljmp last1
up2:   mov b,@r0
       inc r0
       mov a,@r0
       cjne a,b,chk1   ;checking the successive two numbers to arrange in descending order
       ljmp last1
chk1:  jc last1        ; jumping if the two numbers are in descending order
       dec r0          ;swaping if the first number is lesser than second number
       mov @r0,a
       inc r0
       mov @r0,b
last1: djnz r6,up2     ;Comparing the inner counter
       djnz r3,up3     ;comparing the outer counter
       end     

No comments:

Powered by Blogger.