coderx123
coderx123

Reputation: 3

Smallest element in an array

I have written a small program to find the smallest element in an array. I have to use a similar format even though there are much shorter ways to do this. I can't seem to find wha is wrong with the code. The tests are as follows:-

Testing smallest:

array:

Your answer = 2147483647

----pass----

array: 0 -1 5

Your answer = -1

----pass----

array: -1 0 3 -10 3 100

Your answer = 100

----fail----

array: 0 0

Your answer = 0

----pass----

array:

Your answer = 2147483647

----pass----

int smallest(int elements[], int size) {
int i;
int temp1 = 0;
int temp2 = elements[0];
if (size <= 0)
{
  return INT_MAX;
}
else
{
for (i = 0; i<size; i++)
{
  if (elements[i] < temp1)
  {
    elements[i-1] = elements[i];
    temp2 = elements[i];
    elements[i] = temp1;
    temp1 = temp2;
  }
  else
    temp1 = elements[i];
}

return temp1;
}
}

Upvotes: 0

Views: 319

Answers (1)

vrtex
vrtex

Reputation: 165

You need to remember current minimum (it can start equal to array's first element), then just loop through the array. If the current element is less than current minimum change the value of current minimum.

...    
int min = elements[0];
int i;
for (i = 1; i < size; ++i)
    if (elements[i] < min)
        min = elements[i];
...

Upvotes: 5

Related Questions