Learn how to implement selection sort in 32-bit x86 assembly using NASM, with loops, comparisons, and swaps for educational purposes.
section .data
; Definition of the array to sort
array dd 29, 10, 14, 37, 13, 5, 22, 1
array_len equ 8
section .text
global _start
_start:
; ESI = index i (outer loop)
xor esi, esi ; i = 0
outer_loop:
cmp esi, array_len - 1
jge end_sort ; if i >= n-1 end
; EDI = index min_idx = i
mov edi, esi
; ECX = j = i + 1 (inner loop)
mov ecx, esi
inc ecx
inner_loop:
cmp ecx, array_len
jge check_swap ; if j >= n exit inner loop
; Load array[j] into eax
mov eax, [array + ecx*4]
; Load array[min_idx] into ebx
mov ebx, [array + edi*4]
cmp eax, ebx
jge skip_update_min
; If array[j] < array[min_idx], update min_idx = j
mov edi, ecx
skip_update_min:
inc ecx
jmp inner_loop
check_swap:
; If min_idx != i, swap array[i] and array[min_idx]
cmp edi, esi
je no_swap
; Swap:
; Load array[i] into eax
mov eax, [array + esi*4]
; Load array[min_idx] into ebx
mov ebx, [array + edi*4]
; Write array[min_idx] = eax
mov [array + edi*4], eax
; Write array[i] = ebx
mov [array + esi*4], ebx
no_swap:
inc esi
jmp outer_loop
end_sort:
; Program termination
mov eax, 1 ; syscall sys_exit
xor ebx, ebx ; exit code 0
int 0x8032-bit integer array to sort defined in data section
Register ESI: pointer to the current array element
Register EDI: pointer to the found minimum element
Register ECX: loop counter
Register EAX: general-purpose register for comparisons and swaps
Data section: definition of the array and its size
Text section: executable code
Linux x86 32-bit operating system for execution and exit syscall
NASM assembler for compilation (e.g., nasm -f elf32 selection_sort.asm)
ld linker to generate the executable (e.g., ld -m elf_i386 -s -o selection_sort selection_sort.o)
Arduino pinout not applicable as assembly code is for PC x86
Software dependencies: NASM assembler, ld linker, Linux x86 32-bit environment