Find Max Using Linear Search

From CompSciWiki
Revision as of 16:06, 4 December 2011 by JordanW (Talk | contribs)

Jump to: navigation, search

Back to the Program-A-Day homepage

Problem

You are given an array of student marks received on a test. Write a method to find the highest mark received on the test and return this mark.

 

...by students

When I learned about arrays, my professor drew out the array as a long rectangle sliced up into multiple slots. This really helped me to visualize what was in each slot of the array at any given time. I found this very helpful to keep track of the contents of the array and I continue to use drawings whenever using arrays.

Solution

Create a your method with the proper return type and accepted parameter value (array of ints).

 public static int findMax(int[] array) {

} 

Use a variable to keep track of the highest value in the array so far. At the beginning of your method, initialize this variable to 0 since we have not started looking through the array yet.

 int highest = 0; 

Use a for loop to go through each element in the array to check if it is higher than the current value saved as the highest.

 for(i = 0; i < array.length; i++) {

} 

For each element in the array, use an if statement to determine whether it is larger than the current highest variable. In order to determine this, use the '>' operator. If the current element is greater than the highest variable, you can set the highest variable to the current element in the array.

 if(array[i] > highest) {
    highest = array[i];
} 

After the for loop, return your highest variable.

 return highest; 

Putting everything together, here's what your entire method should look like:

 public static int findMax(int[] array) {
    int i; // loop iterator
    int highest = 0;

    for(i = 0; i < array.length; i++) {
        if(array[i] > highest) {
            highest = array[i];
        }
    }

    return highest;
} 

Code

Solution Code

Back to the Program-A-Day homepage