寻找Java数组中最大元素

x33g5p2x  于2022-10-06 转载在 Java  
字(0.8k)|赞(0)|评价(0)|浏览(310)

在这篇文章中,我们将写一个Java程序来寻找一个数组中最大的元素。

在这篇文章中,我们可以通过2种方式来编写逻辑,找到数组中的最大元素。

  • 使用迭代法
  • 使用Arrays.sort()方法

### 使用迭代法

public class LargestNumbersInArray {
 public static void main(final String[] args) {
  
  final int[] array = {12,34,56,12,13,454};
        usingIterative(array);
 }
 
 private static int usingIterative(final int[] array){
   // Initialize maximum element
        int max = array[0];
      
        // Traverse array elements from second and
        // compare every element with current max  
        for (int i = 1; i < array.length; i++){
            if (array[i] > max){
             max = array[i];
            }
        }
        
        System.out.println(max);
        return max;
 }
}

输出。

454

使用Arrays.sort()方法

public class LargestNumbersInArray {
 public static void main(final String[] args) {
  
  final int[] array = {12,34,56,12,13,454};
        final int largest = usingLibrary(array);
        System.out.println(largest);
 }
 
 private static int usingLibrary(final int[] array){
  Arrays.sort(array);
  return array[array.length - 1];
  
 }
}

输出。

454

相关文章

微信公众号

最新文章

更多