Sunday, September 12, 2010

Code for finding the minimum value in an array:


int findMin (int list[])
{
        int minimum = list[0];
        int size = list.length();
        for (int index = 1; index < size; index++)
        {
               if (minimum > list[index])
               {
                        minimum = list[index];
               }
        }
        return minimum;
}

This program assigns the value stored in the first element to minimum and compares it with the next element (if it exists) and if the new value is smaller than the old value it replaces it. next the index is incremented by 1 and a new value is compared. This repeats until every element in the array has been examined.

This algorithm will always terminate as size must always be a positive finite integer and index will eventually no longer be smaller than it

Update 9/13/10:
This program will always return the minimum value because it iteration of the loop compares the value stored in minimum to list[index] and if the new value is smaller the minimum is updated. by the end of the loop minimum will be equal to the smallest value stored in the array.

1 comment:

  1. Perfect.
    You have the algorith, it's explanation, and finiteness proof.
    Only thing missing is a proof of correctness.

    -Aviral

    ReplyDelete