Write a Java program to find the maximum and minimum values in an array.
This program efficiently finds the maximum and minimum values in an array.
class Main {
public static void main(String[] args) {
int[] arr = {2, 6, 8, 5, 6}; // Sample array
findMaxMin(arr); // Call the method to find max and min
}
// Method to find and print the maximum and minimum values in the array
public static void findMaxMin(int[] arr) {
int max = arr[0]; // Initialize max with the first element
int min = arr[0]; // Initialize min with the first element
// Loop through the array to find the max and min values
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i]; // Update max if current element is greater
}
if (arr[i] < min) {
min = arr[i]; // Update min if current element is smaller
}
}
// Print max and min with better formatting
System.out.println("Max: " + max); // Print max on a new line
System.out.println("Min: " + min); // Print min on a new line
}
}
Output:
Max: 8
Min: 2
Key Features
- Initialization:
- Both max and min are initialized to the first element of the array to ensure that they hold valid values for comparison during the iteration.
- Iterative Approach:
- A simple loop starts from the second element (index 1) and compares each element with the current max and min values.
- If the current element is greater than max, it updates max.
- If the current element is smaller than min, it updates min.
- Time Complexity:
- O(n), where n is the size of the array. Each element is checked once.
- Space Complexity:
- O(1), since no additional data structures are used.
Example Execution
Given the array arr = {2, 6, 8, 5, 6}:
- Initial Values:
arduino
Copy code
max = 2, min = 2
- Iteration:
- Index 1 (6): Update max to 6.
- Index 2 (8): Update max to 8.
- Index 3 (5): No updates (5 is between max and min).
- Index 4 (6): No updates.
Why This Method?
- Single Pass: Finds both max and min in a single traversal.
- Efficient: Ideal for scenarios where performance matters and the dataset is large.