The problem is you arbitrary set at the beginning min1
as the first element and min2
as the 2nd element, and then - you start traversing from the first element (temp
).
This makes you read the first 2 elements twice, and if one of them is the minimum - it is also inserted twice, the algorithm 'thinks' you have two elements with the value 1.
The solution to this problem could be following one of the two approaches:
- Set
min1
andmin2
to the first elements, after checking which is indeed smaller, and then start traversing only from the 3rd element - avoid re-reading an element you have already read. - (better solution) set
min1
andmin2
as values that are larger than the range of the elements. A good choice will be usingINT_MAX
- it will ensure your logic is invoked from the first steps of your algorithm.