title: Bubble sort algorithm in MIPS
body: <p>I'm trying to write a procedure in assembly that sorts an array using bubble-sort algorithm but I'm having a problem which is:</p>
  
  <p>In <code>line 22</code>, when the first iteration executed nothing is wrong, program loads <code>array[i+1]</code> perfectly into registrar <code>$a1</code> and if the swap condition is valid, program swaps without any problem. However, in the second iteration, program always loads <code>0</code> into <code>$a1</code> whatever the real value of the element was! I tried debugging it but nothing was clear and I don't know what is the cause of this.</p>
  
  <pre><code>1.  # Procedure:    bubbleSort
  2.  # Objective:    sort an array of integer elements in nondecreasing order
  3.  # Input:        an address of an array of integers
  4.  # Output:       an array sorted in nondecreasing order
  5. 
  6.  bubbleSort:
  7. 
  8.  move    $t0, $a0     # move address of the array into $t0
  9.  li      $s0, 1      # boolean swap = false.  0 --&gt; false, 1 --&gt; true
  10. li      $t1, 0      # j = 0;
  11. li      $t2, 0      # i = 0;
  12. li      $s1, 9      # array length
  13. loop:
  14.     beqz    $s0, exit       # exit if swap = false
  15.     li      $s0, 0          # swap = false;
  16.     addiu   $t1, $t1, 1  # j++;
  17.     move    $t2, $0      # i = 0;
  18.     subu    $s2, $s1, $t1  # s2 = length - j
  19.     forLoop:
  20.         bge     $t2, $s2, exitForLoop   # if i&gt;=s2, exit
  21.         lw      $a0, 0($t0)         # a0 = array[i]
  22.         lw      $a1, 4($t0)         # a1 = array[i+1]
  23.         ble     $a0, $a1, update        # if array[i]&lt;=array[i+1] skip
  24.         sw      $a1, 0($t0)         # a[i+1] = a[i]
  25.         sw      $a0, 4($t0)         # a[i] = a[i+1]
  26.         li      $s0, 1                 # swap = true;
  27.         update:
  28.         addiu   $t2, $t2, 1         # i++
  29.         sll     $t3, $t2, 2         # t3 = i*4
  30.         addu    $t0, $t0, $t3        # point to next element --&gt;
  31.         j       forLoop
  32.     exitForLoop:
  33.         j   loop
  34. exit:
  35.     jr      $ra
  </code></pre>