Skip to content
Related Articles

Related Articles

8085 program for bubble sort
  • Difficulty Level : Medium
  • Last Updated : 07 Jul, 2020

Prerequisite – Bubble Sort
Problem – Write an assembly language program in 8085 microprocessor to sort a given list of n numbers using Bubble Sort.

Example –

Assumption – Size of list is stored at 2040H and list of numbers from 2041H onwards.

Algorithm –

  1. Load size of list in C register and set D register to be 0
  2. Decrement C as for n elements n-1 comparisons occur
  3. Load the starting element of the list in Accumulator
  4. Compare Accumulator and next element
  5. If accumulator is less than or equal to the next element jump to step 8
  6. Swap the two elements
  7. Set D register to 1
  8. Decrement C
  9. If C>0 take next element in Accumulator and go to point 4
  10. If D=0, this means in the iteration, no exchange takes place consequently we know that it won’t take place in further iterations so the loop in exited and program is stopped
  11. Jump to step 1 for further iterations

Program –

AddressLabelInstructionComment
2000HSTARTLXI H, 2040HLoad size of array
2003HMVI D, 00HClear D register to set up a flag
2005HMOV C, MSet C register with number of elements in list
2006HDCR CDecrement C
2007HINX HIncrement memory to access list
2008HCHECKMOV A, MRetrieve list element in Accumulator
2009HINX HIncrement memory to access next element
200AHCMP MCompare Accumulator with next element
200BHJC NEXTBYTEIf accumulator is less then jump to NEXTBYTE
200EHJZ NEXTBYTEIf accumulator is equal then jump to NEXTBYTE
2011HMOV B, MSwap the two elements
2012HMOV M, A
2013HDCX H
2014HMOV M, B
2015HINX H
2016HMVI D, 01HIf exchange occurs save 01 in D register
2018HNEXTBYTEDCR CDecrement C for next iteration
2019HJNZ CHECKJump to CHECK if C>0
201CHMOV A, DTransfer contents of D to Accumulator
201DHCPI 01HCompare accumulator contents with 01H
201FHJZ STARTJump to START if D=01H
2022HHLTHALT

Explanation-

  • Retrive an element in accumulator.
  • Compare it with next element, if it is greater then swap otherwise move to next index.
  • If in one entire loop there has been no exchange, halt otherwise start the whole iteration again.
  • The following approach has two loops, one nested inside other so-

    Worst and Average Case Time Complexity: O(n*n). Worst case occurs when array is reverse sorted.
    Best Case Time Complexity: O(n). Best case occurs when array is already sorted.

My Personal Notes arrow_drop_up
Recommended Articles
Page :