Insertion Sort Algorithm in 8051 Microcontroller Assembly Language

Home » Blog » instrumentation » Insertion Sort Algorithm in 8051 Microcontroller Assembly Language

Here’s an example program in 8051 microcontroller assembly language that uses the insertion sort algorithm to sort an array in place:

ORG 0H        ; start at address 0

MOV DPTR,#3000H ; load address of array into DPTR
MOV R0,#0H     ; initialize outer loop counter
MOV R1,#1H     ; initialize inner loop counter

OuterLoop:
    MOV A,R1   ; load inner loop counter into accumulator
    SUBB A,R0  ; subtract outer loop counter from inner loop counter
    JC End     ; if inner loop counter < outer loop counter, exit loop

    MOV R2,A   ; save inner loop counter
    MOV A,@DPTR+R1 ; load current value from array
    MOV R3,A   ; save value in temporary register

InnerLoop:
    MOV A,@DPTR+R2 ; load value from previous position in array
    CJNE A,ACC,Shift ; if value >= temporary value, shift value right
    MOV @DPTR+R2+1,A ; otherwise, move value right
    DJNZ R2,InnerLoop ; continue loop until start of array is reached
    JMP Insert ; insert temporary value in correct position

Shift:
    MOV @DPTR+R2+1,A ; move value right
    DJNZ R2,InnerLoop ; continue loop until start of array is reached

Insert:
    MOV @DPTR+R2+1,R3 ; insert temporary value in correct position
    INC R1     ; move to next element in array
    SJMP OuterLoop ; continue outer loop until end of array is reached

End:
    ; program exits here

; data section
ORG 3000H
DB 5, 4, 3, 2, 1 ; example array to be sorted

This program assumes that the array to be sorted starts at memory address 3000H and has a length of 5 elements. To sort a different array, you’ll need to modify the data section accordingly.

The program uses two nested loops to compare adjacent elements of the array and swap them if necessary, until the array is sorted in ascending order. The outer loop runs from the first to the second-to-last element of the array, while the inner loop runs from the current element to the beginning of the array. The inner loop compares each element with its predecessor and shifts it right until it finds the correct position for the current element. Finally, the temporary value is inserted in the correct position.

Note that this program sorts the array in place, meaning that it modifies the original array rather than creating a new sorted array.

Leave a Comment

Your email address will not be published. Required fields are marked *