开发者

Extracting three minimums

I want to obtain the minimum 开发者_如何学运维of a double array and the other two minimum values. In total I wan to obtain the 3 smaller values of the array. I am not using the class array, but I am using a double[].


Easiest way is to call

Arrays.sort()

and take the first 3 values.

Otherwise, you can simply loop through the array and keep track of the three smallest, much like you would the smallest.


double[] dlist = {17.0, 10.0, 44, 7, 4.0, 33, 24, 10, 48.0, 49.0};
Arrays.sort (dlist);
System.out.println (dlist [0] + " " + dlist [1] /*...*/);


Similarly to above, you could loop through and store the smallest one, then remove from the array. Then do it again, and again. But I think the ways mentioned above are more efficient.


Well, if you can't use the Arrays class at all, you will probably want 3 variables, one to hold each of the values you are trying to get. Just start off by setting them equal to the first 3 elements in the array (if there are at least 3, otherwise just set a few of them).

Then use a for loop to go through the rest of the elements in the array. If an element is smaller than one or more of the numbers you already found, get rid of the largest of those numbers and add this one to the list of smallest numbers instead.

1. declare 3 variables
2. set variables equal to first 3 elements in array
3. loop from index 3 (4th element) to the length of the array
   a. see which of the already found numbers is bigger than the current element (if any)
   b.replace the biggest of the found numbers with the new number if at least one was found
4. print out or return the numbers you found
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜