微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 最大的5数组的10个数字没有排序

这是我的代码,找到一个数组的最大数字,但我似乎不明白如何获得前5个数字,并将它们存储在数组中,然后检索它们

以下是代码

public class Max {


    public static void main (String[] args) 
    {
        int i;
        int large[]=new int[5];     
        int array[] = {33,55,13,46,87,42,10,34,43,56};
        int max = array[0]; // Assume array[0] to be the max for time-being

        //Looping n-1 times,O(n)
        for(  i = 1; i < array.length; i++) // Iterate through the First Index and compare with max
        {
            // O(1)
            if( max < array[i])
            {
                // O(1)
                max = array[i];// Change max if condition is True
                large[i] = max;
            }
        }
        for (int j = 0; j<5; j++)
        {
            System.out.println("Largest 5 : "+large[j]);
        }
        System.out.println("Largest is: "+ max);
        // Time complexity being: O(n) * [O(1) + O(1)] = O(n)
    }

}

我正在使用一个数组来存储5个数字,但是当我运行它时,它不是我想要的.
任何人都可以帮我吗?

解决方法

看下面的代码
public static void main(String args[]) {
    int i;
    int large[] = new int[5];
    int array[] = { 33,56 };
    int max = 0,index;
    for (int j = 0; j < 5; j++) {
        max = array[0];
        index = 0;
        for (i = 1; i < array.length; i++) {
            if (max < array[i]) {
                max = array[i];
                index = i;
            }
        }
        large[j] = max;
        array[index] = Integer.MIN_VALUE;

        System.out.println("Largest " + j +  " : " + large[j]);
    }
}

注意:如果您不想更改输入的数组,请复制它并对复制的数组执行相同的操作.

看看Integer.MIN_VALUE.

我得到以下输出

Largest 0 : 87

Largest 1 : 56

Largest 2 : 55

Largest 3 : 46

Largest 4 : 43

原文地址:https://www.jb51.cc/java/125047.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐