0

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;
}
}
3
  • Please fix your indenting Commented Jan 23, 2019 at 21:52
  • 1
    I don't understand why it is that complicated. You only need to scan the array and compare each element to the currently found minimum. Commented Jan 23, 2019 at 21:52
  • 2
    Why are you changing the array? You're doing more work than expected. Commented Jan 23, 2019 at 21:55

1 Answer 1

5

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];
...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.