TExcelTAD
Home › x86-64 Assembly › Sorting an Array

Sorting an Array

Sorting is a perfect exercise for everything so far: nested loops, array indexing, comparisons and swaps. This lesson implements three classic algorithms in assembly and finishes with binary search, which needs a sorted array.

Bubble sort

Bubble sort walks through the array again and again, swapping neighbours that are in the wrong order. After each pass the largest remaining element has "bubbled" to the end. If a pass makes no swaps, the array is sorted and we can stop early.

nasm · try it yourself
section .data
scores:     dq 29, 10, 14, 37, 13, 5, 22
COUNT       equ ($ - scores) / 8

section .text
global _start
_start:
    mov rdi, scores
    mov esi, COUNT
    call print_array            ; before

    mov r8d, COUNT - 1          ; the last index this pass compares up to
.pass:
    xor r9d, r9d                ; swapped = false
    xor ecx, ecx                ; i = 0
.compare:
    mov rax, [scores + rcx*8]
    mov rdx, [scores + rcx*8 + 8]
    cmp rax, rdx
    jbe .in_order               ; scores[i] <= scores[i+1]: fine
    mov [scores + rcx*8], rdx   ; swap the neighbours
    mov [scores + rcx*8 + 8], rax
    mov r9d, 1                  ; swapped = true
.in_order:
    inc ecx
    cmp ecx, r8d
    jb .compare
    test r9d, r9d
    jz .sorted                  ; a pass without swaps: done
    dec r8d                     ; the last element is in place now
    jnz .pass
.sorted:
    mov rdi, scores
    mov esi, COUNT
    call print_array            ; after

    mov eax, 60
    xor edi, edi
    syscall

; ---- print_array: print rsi unsigned quadwords starting at rdi on one line ----
print_array:
    push rbx
    push r12
    mov rbx, rdi            ; rbx = address of the next element
    mov r12, rsi            ; r12 = elements left
    sub rsp, 32             ; digit buffer, as in print_uint
.element:
    test r12, r12
    jz .finish
    mov rax, [rbx]          ; the number to convert
    lea rsi, [rsp + 31]
    mov byte [rsi], ' '     ; a space after each number ...
    cmp r12, 1
    jne .convert
    mov byte [rsi], 10      ; ... except the last one, which ends the line
.convert:
    mov ecx, 10
.digit:
    xor edx, edx
    div rcx
    add dl, '0'
    dec rsi
    mov [rsi], dl
    test rax, rax
    jnz .digit
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; length of digits + separator
    mov eax, 1
    mov edi, 1
    syscall
    add rbx, 8              ; next quadword
    dec r12
    jmp .element
.finish:
    add rsp, 32
    pop r12
    pop rbx
    ret
29 10 14 37 13 5 22
5 10 13 14 22 29 37

Note the unsigned comparison jbe: print_array prints unsigned values, and these scores are never negative. To sort signed numbers, change jbe to jle.

Insertion sort

Insertion sort builds a sorted prefix. Each new element is taken out ("the key") and larger elements of the prefix are shifted one place right until the key's position is found. It is fast for small or nearly sorted arrays, which is why real-world sort functions switch to it for short ranges.

nasm · try it yourself
section .data
data:       dq 8, 3, 9, 1, 7, 2, 6
COUNT       equ ($ - data) / 8

section .text
global _start
_start:
    mov ecx, 1                  ; i = 1
.outer:
    mov rax, [data + rcx*8]     ; key = data[i]
    mov rdx, rcx                ; j = i
.shift:
    test rdx, rdx
    jz .insert                  ; reached the front
    mov r8, [data + rdx*8 - 8]  ; data[j - 1]
    cmp r8, rax
    jbe .insert                 ; data[j-1] <= key: found the spot
    mov [data + rdx*8], r8      ; shift data[j-1] one place right
    dec rdx
    jmp .shift
.insert:
    mov [data + rdx*8], rax     ; data[j] = key
    inc ecx
    cmp ecx, COUNT
    jb .outer

    mov rdi, data
    mov esi, COUNT
    call print_array

    mov eax, 60
    xor edi, edi
    syscall

; ---- print_array: print rsi unsigned quadwords starting at rdi on one line ----
print_array:
    push rbx
    push r12
    mov rbx, rdi            ; rbx = address of the next element
    mov r12, rsi            ; r12 = elements left
    sub rsp, 32             ; digit buffer, as in print_uint
.element:
    test r12, r12
    jz .finish
    mov rax, [rbx]          ; the number to convert
    lea rsi, [rsp + 31]
    mov byte [rsi], ' '     ; a space after each number ...
    cmp r12, 1
    jne .convert
    mov byte [rsi], 10      ; ... except the last one, which ends the line
.convert:
    mov ecx, 10
.digit:
    xor edx, edx
    div rcx
    add dl, '0'
    dec rsi
    mov [rsi], dl
    test rax, rax
    jnz .digit
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; length of digits + separator
    mov eax, 1
    mov edi, 1
    syscall
    add rbx, 8              ; next quadword
    dec r12
    jmp .element
.finish:
    add rsp, 32
    pop r12
    pop rbx
    ret
1 2 3 6 7 8 9

Selection sort as a function

Wrapping a sort in a function that follows the calling convention makes it reusable: selection_sort(array, count). It finds the smallest remaining element and swaps it to the front of the unsorted part. Only scratch registers are used, so nothing needs saving:

nasm · try it yourself
section .data
first:      dq 50, 20, 40, 10, 30
second:     dq 3, 1, 2

section .text
global _start
_start:
    mov rdi, first
    mov esi, 5
    call selection_sort
    mov rdi, first
    mov esi, 5
    call print_array

    mov rdi, second
    mov esi, 3
    call selection_sort
    mov rdi, second
    mov esi, 3
    call print_array

    mov eax, 60
    xor edi, edi
    syscall

; selection_sort(rdi = array of unsigned quadwords, rsi = count)
selection_sort:
    xor ecx, ecx                ; i = 0
.next_position:
    lea rax, [rcx + 1]
    cmp rax, rsi
    jae .done                   ; i + 1 >= count: finished
    mov r8, rcx                 ; min_index = i
    mov rdx, rax                ; j = i + 1
.find_min:
    mov r9, [rdi + rdx*8]
    cmp r9, [rdi + r8*8]
    jae .not_smaller
    mov r8, rdx                 ; new min_index
.not_smaller:
    inc rdx
    cmp rdx, rsi
    jb .find_min
    mov r9, [rdi + rcx*8]       ; swap array[i] and array[min_index]
    mov r10, [rdi + r8*8]
    mov [rdi + rcx*8], r10
    mov [rdi + r8*8], r9
    inc rcx
    jmp .next_position
.done:
    ret

; ---- print_array: print rsi unsigned quadwords starting at rdi on one line ----
print_array:
    push rbx
    push r12
    mov rbx, rdi            ; rbx = address of the next element
    mov r12, rsi            ; r12 = elements left
    sub rsp, 32             ; digit buffer, as in print_uint
.element:
    test r12, r12
    jz .finish
    mov rax, [rbx]          ; the number to convert
    lea rsi, [rsp + 31]
    mov byte [rsi], ' '     ; a space after each number ...
    cmp r12, 1
    jne .convert
    mov byte [rsi], 10      ; ... except the last one, which ends the line
.convert:
    mov ecx, 10
.digit:
    xor edx, edx
    div rcx
    add dl, '0'
    dec rsi
    mov [rsi], dl
    test rax, rax
    jnz .digit
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; length of digits + separator
    mov eax, 1
    mov edi, 1
    syscall
    add rbx, 8              ; next quadword
    dec r12
    jmp .element
.finish:
    add rsp, 32
    pop r12
    pop rbx
    ret
10 20 30 40 50
1 2 3

Binary search

Once an array is sorted, you can find a value in log2(n) steps: compare with the middle element and throw away the half that can't contain it. The function returns the index, or −1 when the value is missing:

nasm · try it yourself
section .data
sorted:     dq 3, 8, 15, 23, 42, 56, 71, 89, 94
COUNT       equ ($ - sorted) / 8

section .text
global _start
_start:
    mov edi, 42
    call find
    mov rdi, rax
    call print_int              ; index of 42

    mov edi, 50
    call find
    mov rdi, rax
    call print_int              ; not present

    mov eax, 60
    xor edi, edi
    syscall

; find(rdi = value) -> index in sorted[], or -1
find:
    xor ecx, ecx                ; low = 0
    mov edx, COUNT              ; high = count (exclusive)
.loop:
    cmp rcx, rdx
    jae .missing                ; empty range
    lea rax, [rcx + rdx]
    shr rax, 1                  ; mid = (low + high) / 2
    cmp rdi, [sorted + rax*8]
    je .found
    jb .left
    lea rcx, [rax + 1]          ; value > middle: low = mid + 1
    jmp .loop
.left:
    mov rdx, rax                ; value < middle: high = mid
    jmp .loop
.found:
    ret                         ; rax = mid
.missing:
    mov rax, -1
    ret

; ---- print_int: print rdi as a signed decimal number and a newline ----
print_int:
    test rdi, rdi
    jns print_uint          ; not negative: print it as it is
    neg rdi                 ; make it positive
    push rdi                ; keep it (write and syscall clobber registers)
    push '-'                ; the minus sign, as a byte on the stack
    mov eax, 1              ; write(1, rsp, 1)
    mov edi, 1
    mov rsi, rsp
    mov edx, 1
    syscall
    pop rdi                 ; drop the '-'
    pop rdi                 ; the positive value again
    jmp print_uint          ; print_uint's ret returns to our caller

; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
    mov rax, rdi            ; rax = the number to convert
    sub rsp, 32             ; room for up to 20 digits and a newline
    lea rsi, [rsp + 31]     ; fill the buffer from its end
    mov byte [rsi], 10      ; the newline is the last character
    mov ecx, 10
.next_digit:
    xor edx, edx            ; the dividend is rdx:rax, so clear rdx
    div rcx                 ; rax = quotient, rdx = remainder (0..9)
    add dl, '0'             ; remainder -> ASCII digit
    dec rsi
    mov [rsi], dl           ; store it in front of the previous one
    test rax, rax
    jnz .next_digit         ; repeat until the quotient is 0
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; rdx = number of bytes to print
    mov eax, 1              ; write(1, rsi, rdx)
    mov edi, 1
    syscall
    add rsp, 32
    ret
4
-1

Notice je and jb after a single cmp: the flags stay valid until another instruction changes them, so one comparison can feed several jumps.

Which sort to use?

Algorithm Comparisons (average) Good for
bubble sort ~n²/2 teaching; detecting "already sorted"
insertion sort ~n²/4 small or nearly sorted arrays
selection sort ~n²/2 few swaps (exactly n − 1)
quicksort / merge sort ~n log n everything large

Test yourself

In the bubble sort, what does the swapped flag (r9) allow?

  1. Sorting signed numbers
  2. Stopping early when a pass made no swaps
  3. Sorting in descending order
  4. Skipping the first element

To sort signed numbers in ascending order, which jump should the bubble sort use after cmp rax, rdx?

  1. jbe
  2. jle
  3. ja
  4. jg

How many comparisons does binary search need at most for 9 sorted elements?

  1. 9
  2. 4
  3. 2
  4. 81