So ... I have : int array[] = {-8,2,0,5,-3,6,0,9};
I want to find the smallest positive number ( which in the list above is 2 )
This is what i am doing :
int array[] = {-8,2,0,5,-3,6,0,9};
int smallest=0;
for(int i=0;i<array.length;i++) // Find the first number in array>0 (as initial
// value for int smallest)
{
if(array[i]>0)
{
smallest=array[i];
break;// Break out of loop, when you find the first number >0
}
}
for(int i=0;i<array.length;i++) // Loop to find the smallest number in array[]
{
if(smallest>array[i]&&array[i]>0)
{
smallest=array[i];
}
}
System.out.println(smallest);
}
My question is :
Can we reduce the number of steps ? Is there any smarter/shorter way of doing it, with no other data structure.
Thanks.