Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #MIPS bubble sort example, written+tested in MARS 4.5 simulator, with "delayed branching OFF"
- # (with delayed branching ON (real MIPS CPU) this will produce incorrect results)
- .data
- .eqv array_len, 4
- array: .word 5, 4, 3, 2
- # array: .word 5, 4, 2, 3
- # array: .word 2, 3, 4, 5
- .text
- main:
- la $t0, array # t0 = array address (first element)
- li $t1, array_len
- sll $t1, $t1, 2 # length * 4 (sizeof word)
- add $t1, $t0, $t1 # t1 = address beyond array (after last element)
- bubble_out_loop:
- addiu $t1, $t1, -4 # t1 = address of (new) last element (every iteration one less)
- beq $t0, $t1, bubble_finish # if last element to consider is also first element, stop
- addiu $t2, $t0, 4 # t2 = second element address (initialization for inner loop)
- lw $t3, ($t0) # t3 = current first element
- bubble_pair_loop:
- lw $t4, ($t2) # t4 = next element
- ble $t3, $t4, bubble_pair_no_swap # if t3 <= t4, don't swap
- # swap the elements in memory
- sw $t4, -4($t2)
- sw $t3, 0($t2)
- move $t4, $t3 # partial swap in registers (only t4 "next" updated, t3 is wrong)
- bubble_pair_no_swap:
- beq $t2, $t1, bubble_out_loop # if "next" address was equal to "last", inner loop is finished
- # check next pair of elements
- addiu $t2, $t2, 4 # advance "next" pointer
- move $t3, $t4 # "next" element will be now "previous" for next pair
- j bubble_pair_loop
- bubble_finish:
- li $v0, 10
- syscall
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement