Sorting an Array

For this assignment you will write a MAL subprogram sortArray for sorting an array of integers. In order to check the correctness of your code, you will need a test array and you will also need to write a subprogram printArray to display the contents of the array. Finally, you will write a short main program that calls the subprograms.

In this program you will get experience working with static arrays and sequential array access.

The Test Array

It is useful to be able to declare an array with initialized entries. You can accomplish this by just declaring the entries individually. For example, the following declarations declare an array testArray with three entries, whose values are 5, 2, and 7.

testArray:
    .word   5
    .word   2
    .word   7

The printArray subprogram

After decrlaring a test array, the best place to start writing code is a function printArray to display an array of integers. This function has two parameters:

The entries should be printed one per line.

The simplest way to handle addresses is to increment the array address parameter by 4 each time through the printing loop. Since this changes the parameter, the caller should set the parameter each time the function is called using the la instruction.

The printArray function should be tested before proceeding further. Just add a main program that declares an array as shown above and calls printArray.

The sortArray Subprogram

You can use any non-recursive algorithm for sorting. Here is one simple algorithm:

void sortArray(int A[], int entryCount) {
  int i;
  int j;
  int temp;
  for (i = entryCount - 1; i > 0; i--) {
    for (j = 0; j < i; j++) {
      if (A[j + 1] < A[j]) {
        temp = A[j];
        A[j] = A[j + 1];
        A[j + 1] = temp;
      }
    }
  }
}

Whatever algorithm you use, it will save you time in the long run if you spend extra time working out the conversion to MAL.

The main program

The main program should print an array declared as described above, call the sort subprogram, then print the array again.

Testing your program

You should do testing incrementally. First write the printArray subprogram and a simplified main program to test it. When that is working, write the sortArray subprogram and modify the main program to test it.

You should try your program with array entries in various orders. Starting with the entries in reverse order gives a good test for the sort algorithm described earlier. Changing the number of entries that you sort can give you some indication of off-by-one errors.

What to Turn in

Turn in both a copy of your program and a Mars session record. In this session, you should use a test array declared as follows:

testArray:
    .word   9
    .word   8
    .word   7
    .word   4
    .word   5
    .word   6
    .word   3
    .word   2
    .word   1
    .word   0

Your TA may also ask you to demonstrate your program in lab.

References