Java教程

Java查找数组中的最小数字

通过对数组进行排序并返回第一个元素,我们可以在Java中找到数组中最小的元素或数字。我们来看完整的示例,以找到java数组中最小的数字。
public class SmallestInArrayExample{
    public static int getSmallest(int[] a, int total){
        int temp;
        for (int i = 0;i <total;i++) {
            for (int j = i + 1;j <total;j++) {
                if (a[i] >a[j]) {
                    temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                }
            }
        }
        return a[0];
    }
    public static void main(String args[]){
        int a[]={1,2,5,6,3,2};
        int b[]={44,66,99,77,33,22,55};
        System.out.println("Smallest: "+getSmallest(a,6));
        System.out.println("Smallest: "+getSmallest(b,7));
    }
}
输出:
Smallest: 1Smallest: 22

使用数组查找数组中的最小数字

让我们看看另一个示例,使用数组获取Java数组中的最小元素或数字。
import java.util.*;
public class SmallestInArrayExample1{
    public static int getSmallest(int[] a, int total){
        Arrays.sort(a);
        return a[0];
    }
    public static void main(String args[]){
        int a[]={1,2,5,6,3,2};
        int b[]={44,66,99,77,33,22,55};
        System.out.println("Smallest: "+getSmallest(a,6));
        System.out.println("Smallest: "+getSmallest(b,7));
    }
}
输出:
Smallest: 1Smallest: 22

使用集合查找数组中的最小数字

让我们看看另一个示例,使用集合获取java数组中的最小数字。
import java.util.*;
public class SmallestInArrayExample2{
    public static int getSmallest(Integer[] a, int total){
        List <Integer> list=Arrays.asList(a);
        Collections.sort(list);
        int element=list.get(0);
        return element;
    }
    public static void main(String args[]){
        Integer a[]={1,2,5,6,3,2};
        Integer b[]={44,66,99,77,33,22,55};
        System.out.println("Smallest: "+getSmallest(a,6));
        System.out.println("Smallest: "+getSmallest(b,7));
    }
}
输出:
Smallest: 1Smallest: 22
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4