Finding the Max and Min values of a 10 element array in MIPS

user3554599 picture user3554599 · Oct 20, 2014 · Viewed 18.1k times · Source

I am still very much a newbie once it comes to MIPS programming so bear with me. I am trying to write a function that goes through a 10 element array and returns the max and minimum values of the array. So far I have:

.data

X .word 31, 17, 92, 46, 172, 208, 13, 93, 65, 112
N .word 10
minValue .asciiz "Minimum Value: "
maxValue .asciiz "\nMaximum Value: "
values .asciiz "\nValues divisible by 4: "


.text

main:

la $a0, X
la $a1, N


jal MaxMin


MaxMin:
lw $t0, 0($a0)


swap:
move $t0, $s0
move $s0, $s1
move $s0, $t0

The MaxMin function is supposed to return the maximum and minimum values of the X array for me to print out. My plan is to go through the array and if an element is greater than or less than another element, they get swapped using the swap function. The problem is I have no idea how to go about doing this because I do not really know the syntax that you are supposed to use when dealing with arrays. If anyone could help I would appreciate it.

Answer

EOF picture EOF · Oct 21, 2014

How about writing the algorithm in C first?

#include <stddef.h>

struct minmax
{
int max;
int min;
};

struct minmax maxmin(int const *in, size_t n)
{
  struct minmax ret = {*in,*in};
  for (size_t i = 1; i<n; i++)
  {
    in++;
    if (*in > ret.max)
      {
        ret.max = *in;
      }
    if (*in < ret.min)
      {
        ret.min = *in;
      }
  }
  return ret;
}

To iterate over an array in the equivalent MIPS-assembly, you can load the pointer in into a temporary register:

la $t0, in

then dereference the pointer by loading the value from memory:

lw $t1, ($t0)

and finally increment the pointer in the loop:

addiu $t0, $t0, 4