A bubble sort in Assembler

Bubble Sort in X86 Assembler

Since I posted on how to create a bubble sort in Cobol I thought I’d follow with another language. Below is an example of a Bubble Sort algorithm implemented in x86 Assembly language:

section .data
    array db 85, 36, 95, 29, 12, 55, 42, 68, 25, 80
    arraySize equ 10

section .text
    global _start

_start:
    ; Outer loop: loop through the array elements
    mov ecx, arraySize

outerLoop:
    ; Reset the index for the inner loop
    mov ebx, 0

innerLoop:
    ; Compare the current element with the next element
    mov al, [array + ebx]
    cmp al, [array + ebx + 1]
    jle noSwap  ; Jump if the current element <= next element

    ; Swap the elements
    xchg al, [array + ebx + 1]
    mov [array + ebx], al

noSwap:
    ; Increment the inner loop index
    inc ebx
    cmp ebx, ecx
    jl innerLoop  ; Jump if inner loop index < arraySize

    ; Decrement the outer loop counter
    dec ecx
    jnz outerLoop ; Jump if outer loop counter != 0

    ; Done sorting, exit the program
    mov eax, 1     ; syscall number for exit
    xor ebx, ebx   ; exit code 0
    int 0x80       ; invoke syscall

section .bss
    ; No need for any variables in the BSS section for this example

Please note that this example uses x86 Assembly language syntax for Linux. If you intend to use this code in a different environment, you may need to adjust the system calls and assembly syntax accordingly. The provided code demonstrates a simple Bubble Sort algorithm for an array of 10 elements. You can modify the array and arraySize variables to work with different datasets.

Leave a Reply

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