Java程序查找数组中的最大元素
给定一个数组,找出其中最大的元素。
Input : arr[] = {10, 20, 4}
Output : 20
Input : arr[] = {20, 10, 20, 4, 100}
Output : 100
方法一:迭代方式
// Java Program to find maximum in arr[]
class Test
{
static int arr[] = {10, 324, 45, 90, 9808};
// Method to find maximum in arr[]
static int largest()
{
int i;
// Initialize maximum element
int max = arr[0];
// Traverse array elements from second and
// compare every element with current max
for (i = 1; i < arr.length; i++)
if (arr[i] > max)
max = arr[i];
return max;
}
// Driver method
public static void main(String[] args)
{
System.out.println("Largest in given array is " + largest());
}
}
输出:
Largest in given array is 9808
方法 2: Java 8 流
您可以简单地使用新的Java 8 Streams,但必须使用 int。
import java.util.Arrays;
public class GFG {
public static void main(String[] args){
int arr[] = {10, 324, 45, 90, 9808};
int max = Arrays.stream(arr).max().getAsInt();
System.out.println("Largest in given array is " +max);
}
}
输出:
Largest in given array is 9808
方法3:(排序)
// Java program to find maximum in
// arr[] of size n
import java .io.*;
import java.util.*;
class GFG
{
// returns maximum in arr[] of size n
static int largest(int []arr,
int n)
{
Arrays.sort(arr);
return arr[n - 1];
}
// Driver code
static public void main (String[] args)
{
int []arr = {10, 324, 45,
90, 9808};
int n = arr.length;
System.out.println(largest(arr, n));
}
}
有关更多详细信息,请参阅有关程序以查找数组中最大元素的完整文章!