Search code examples
arraysassemblymipsmergesort

Finding midpoint of array in MIPS - Merge sort


I'm trying to create a merge sort algorithm in MIPS and I've identified a bug in my code. In my program, I'm keeping references to the start point and end point of my array ($a0 and $a1 respectively). I'm also keeping track of its length as $a1 - $a0 + 4. The problem is that I don't know how to calculate the midpoint of the array correctly. I need to do so for these equivalent function calls in C:

mergesort(a, start, mid);
mergesort(a, mid + 1, end);

I'm new to MIPS so I'm not exactly sure how you do the arithmetic with 4-bit addresses. I can't add them as ($a0 + $a1)/2 since adding two addresses will cause overflow.

My array is declared up on top as this:

array: .word 0:15

I can assume that not more than 15 numbers will be entered. $s0 (the pointer to the start of the array), $s1 (the pointer to the space AFTER the last element), $a0 (the starting point argument), and $a1 (the end point argument) are all stored like this:

la $s0, array
move $s1, $s0 // $s1 increments by 4 each time an element is added
...
move $a0, $s0
addi $a1, $s1, -4 // subtract four because we want to refer to the last element

How can I calculate the mid index of that array given $a0 and $a1 as references? Any help would be appreciated. Thanks!


Solution

  • ($a0 + $a1) / 2 = $a0 + ($a1 - $a0) / 2 and you won't have any overflow.