PDA

View Full Version : I'm Stuck on 2 Smallest #'s.....


TreeMoney
06-29-2006, 06:15 AM
I'm trying to study for an exam, and I've written this program which finds the 2 smallest numbers out of a list. It works as long as the lowest # isn't first., I can't figure it out. Any ideas?? Thanks in advance.

public class Smallest
{
public static void main(String[] args)
{

int numNums, number, count, small, smallest;
numNums = IO.readInt();

if (numNums<0)
{
IO.reportBadInput();
}
int temp = IO.readInt();
small= temp;
smallest= temp;
count = 1;

while (count < numNums)
{
number = IO.readInt();
count++;

if(number<smallest)
{
temp = smallest;
small = temp;
smallest = number;
}

else {
if (number<small)
{
small = number;
}
}
}

IO.printInt(small);
IO.printInt(smallest);
}
}

mkeehan
06-29-2006, 11:21 AM
Hi TreeMoney,

You could make life a lot easier by implementing a bubblesort :


for (int i = 0; i < a.length ; i++) {
for (int j = a.length-1; j>i ; j--){
if (a[i-1] > a[i]){
int temp = a[i];
a[i] = a[i-1];
a[i-1] = temp;
}
}
}


Your lowest values are then a[0], a[1] etc.

Here's a good java example: http://www.ee.unb.ca/brp/lib/java/bubblesort/

Roelf
06-29-2006, 01:07 PM
that is because the first number is stored in both small and smallest, that way, there is never a number smaller than small, but bigger than smallest. So smallest is correct then, but small isn't.

A straightthrough way of solving it, is when a number is entered, check if small and smallest are the same, this is the case after the first number is entered. If the number is bigger than small and smallest, you should enter this bigger number in small, and leave smallest the same. If this number is smaller than smallest, you should enter it in smallest. If the small and smallest are not the same, handle the number the way you are doing now.