Advertisement
Guest User

MIPS "bubble sort" example for MARS/SPIM simulators

a guest
Aug 20th, 2018
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #MIPS bubble sort example, written+tested in MARS 4.5 simulator, with "delayed branching OFF"
  2. # (with delayed branching ON (real MIPS CPU) this will produce incorrect results)
  3. .data
  4.      .eqv array_len, 4
  5.      array: .word 5, 4, 3, 2
  6. #     array: .word 5, 4, 2, 3
  7. #     array: .word 2, 3, 4, 5
  8. .text
  9.     main:
  10.         la     $t0, array        # t0 = array address (first element)
  11.         li     $t1, array_len
  12.         sll    $t1, $t1, 2       # length * 4 (sizeof word)
  13.         add    $t1, $t0, $t1     # t1 = address beyond array (after last element)
  14.     bubble_out_loop:
  15.         addiu  $t1, $t1, -4      # t1 = address of (new) last element (every iteration one less)
  16.         beq    $t0, $t1, bubble_finish  # if last element to consider is also first element, stop
  17.         addiu  $t2, $t0, 4       # t2 = second element address (initialization for inner loop)
  18.         lw     $t3, ($t0)        # t3 = current first element
  19.     bubble_pair_loop:
  20.         lw     $t4, ($t2)        # t4 = next element
  21.         ble    $t3, $t4, bubble_pair_no_swap   # if t3 <= t4, don't swap
  22.        # swap the elements in memory
  23.        sw     $t4, -4($t2)
  24.        sw     $t3, 0($t2)
  25.        move   $t4, $t3          # partial swap in registers (only t4 "next" updated, t3 is wrong)
  26.    bubble_pair_no_swap:
  27.        beq    $t2, $t1, bubble_out_loop  # if "next" address was equal to "last", inner loop is finished
  28.        # check next pair of elements
  29.        addiu  $t2, $t2, 4       # advance "next" pointer
  30.        move   $t3, $t4          # "next" element will be now "previous" for next pair
  31.        j      bubble_pair_loop
  32.        
  33.    bubble_finish:
  34.        li   $v0, 10
  35.        syscall
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement