Homework 4

Write a program which will demonstrate your ability to properly handle subroutine in MIPS assembly language. This program should generate a a list of 100 random integers between 0 and 1000. It should then sort this list. The list should be printed out. Finally you should demonstrate your search routine by searching for a series of numbers.

A random number generator

First you will need to write code to generate random numbers. Please implement both a void srand (x,y,s) and a int rand() function. Gruenberger and Jaffray in their 1965 book "Problems for Computer Solution" provide the following algorithm for generating random numbers:
srand
  1. Initialize x y and S to user supplied values.
rand
  1. x = x + x
  2. if (x > p) {
  3. x = x - p
  4. }
  5. y = y + y
  6. if (y > q) {
  7. y - y - q
  8. }
  9. S = S + x
  10. S = S + y
  11. Set the top bit of S to be 0.
  12. Return S.
A few notes from the text are in order here:

Mod

You will need code to perform the mod operation. MIPS provides an integer divide instruction.
div $ra, $rb
$lo = $ra/$rb
$hi = $ra % $r
You don't have direct access to the high and low registers, you need to use
mfhi $reg
mflo $reg
To move the value from either high or low to a register of your choice. The code
addi     $t2, $zero, 20
addi     $t3, $zero, 3
div      $t2, $t3
mfhi     $t4
Should compute 20%3 (2) and store the results in register t4.

You should write a routine int mod(a,b) which will return a%b

Sort

You may implement any sort routine you wish.

Search

You must implement a binary search. Your routine must implement bool bsearch(int a[], int low, int high, int key). You must implement a recursive version of this search:
bool bsearch(int a[], int low, int high, int key) {
    if (low > high) {
       return false;
    }
    int mid = (low+high)/2
    if (a[mid] == key) {
       return true;
    } else if (a[mid] > key) {
       return (bsearch(a, low, mid-1, key));
    } else {
       return (bsearch(a, mid+1, high, key));
    }
}

The final product

Your program should implement the following code:

// other constants and procedures and such

void testSearch(int a[], int arraySize, int key) {
    cout << "Searching and " << key << " was ";
    if (!bsearch(a, 0, arraySize-1, key) {
       cout << "NOT " 
    }
    cout << "found." << endl;
}

int main() {
   srand(214159265,  271828183, 0)

   for (i=0;i<MAX;i++) {
      a[i] = rand() % SIZELIMIT
   }
   cout << "Before sorting: " << endl;
   printArray(a, MAX)
   sort(a, MAX) // the sort routine may take on other parameters.
   cout << "After sorting: " << endl;
   printArray(a, MAX)
   testSearch(a, MAX, a[4]);
   testSearch(a, MAX, a[4]+1);
}

Final Note

If you need help on any part of this assignment, ask for it.