Initialize an integer value of "largest" to the first value of the array. Begin a loop to search through the entire array. Within the loop the value of "largest" will be compared to each value within the array sequentially. If, at any time, the array value is larger than "largest", then "largest" will have its value set to the larger array value.
An array with 40 values:
int array[40];
int largest = int array[0];
for(int a=0; a<40; a++)
{
if(array[a] > large)
largest = array[a];
}
The algorithm will work as it will always go through the entire array and will set the variable "largest" to the largest value in the array it comes across. It will also finish in finite time (n-1 time), as it needs only to loop through and compare all the values to "largest" once to find the largest value in the array.
Perfect.
ReplyDelete