10个数字数组中最大的5个,不进行排序
问题内容:
这是我的代码,用于在数字数组中查找最大数,但是我似乎无法理解如何获取前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, 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]);
}
}
注意: 如果您不想更改输入的数组,请对其进行复制并在复制的数组上执行相同的操作。
我得到以下输出:
最大0:87
最大的1:56
最大2:55
最大的3:46
最大4:43