5最大的10个号码数组不排序 [英] Largest 5 in array of 10 numbers without sorting

查看:136
本文介绍了5最大的10个号码数组不排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的code找到数字数组的最大数,但我似乎无法理解如何获得前5个号码,并将其存储在一个数组,以后再取出来。

Here's my code to find the max number in an array of numbers, but i can't seem to understand how to get the top 5 numbers and store them in an array and later retrieve them

这里的code:

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个号码,但是当我运行它,它不是我想要的。 任何人都可以帮助我的计划?

I'm using an array to store 5 numbers, but when i run it, it is not what i want. Can anyone help me with the program?

推荐答案

看下面的code:

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 = 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]);
    }
}

注意:如果您不想改变输入数组,然后做一个副本,做同样的操作复制的阵列上

Note: If you don't want to change the inputted array, then make a copy of it and do the same operation on the copied array.

看看 Integer.MIN_VALUE的

我得到以下的输出:

最大的0:87

最大1:56

最大2:55

最大3:46

最大4:43

这篇关于5最大的10个号码数组不排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆