Sunday, February 16, 2014

Find Maximum Value in the unsorted array

Problem : 
Find Maximum Value in the unsorted array

Solution
Method 1 - Linear search

Here is the code to do that :
public int findMax(int[] numbers)
{
    int max = 0;

    for (int i = 0; i < numbers.length; ++i)
        if (numbers[i] > max) max = numbers[i];

    return max;
}

So, in worst case the number of comparisons will be (n-1).

Time complexity - O(n)

Reactions:

0 comments:

Post a Comment