Java Program to find largest number of an array .
Objective
Write a Java program to find the largest number in an array.
Algorithm / Approach
- Define a method
max(int[] a). - Initialize a variable
maxwith the first element of the array (a[0]). - Start a
forloop fromi = 0toa.length - 1. - Inside the loop, check if the current element
a[i]is greater thanmax. - If true, update
maxwitha[i]. - After checking all elements, print
max.
Test.java
class Test {
void max(int[] a) {
int max = a[0];
for(int i = 0; i< a.length; i++) {
if(max < a[i]) {
max = a[i];
}
}
System.out.print("Max = "+max);
}
public static void main(String[] a)
{
int[] ar = {34,23,67,45,23};
Test t = new Test();
t.max(ar);
}
}
Expected Output
Max = 67
Explanation of the Program
- This algorithm uses the "King of the Hill" approach. We assume the first element is the largest.
- We then challenge this assumption by comparing it against every other element in the array.
- Whenever we find an element larger than our current maximum, we dethrone the old maximum and store the new champion.
- By the time we reach the end of the array, the variable is guaranteed to hold the absolute largest value.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)