chinoy
chinoy

Reputation: 172

Fast algorithm to determine a negative number in a given array

Please suggest if there is quicker way to find the negative number in a given array, provided that the array has only one negative number. I think sorting is an option, but it will be helpful if there is a quicker way.

Upvotes: 0

Views: 231

Answers (3)

Jerry Coffin
Jerry Coffin

Reputation: 490633

Probably the fastest is to just scan the array until you find it.

If you're just doing this once, and don't need the array sorted for other purposes, it'll be faster to scan for the negative number than to do the sort. If, however, you need (or can use) the sorting for other purposes, or you may need to find the negative number several times, then sorting can end up saving time. Likewise, with some programs, spending extra time in preparation to get faster response when really crucial can be justified (but I've no idea whether that applies here or not).

Upvotes: 0

AdrienNK
AdrienNK

Reputation: 848

Sorting won't be quicker than going through all the elements of the array (because to sort you also have to do that).

The fastest possible thing to do is to go through the all array and stop once you detect one negative number.

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234875

Just traverse the array. That is order n. Sorting is at best order n(log n); at worst n2.

Upvotes: 0

Related Questions