Reputation: 1122
I had gone through many articles over internet to find minimum number in an array. According to article they iterate an array n number of times but purpose can be achieve n/2 + 1 iteration
Here is my code
for index in range(0, int(len(myArray)/2)+1):
if minNum > myArray[index]:
minNum = myArray[index]
lastElement = - index - 1
if minNum > myArray[lastElement]:
minNum = myArray[lastElement]
Article code
for element in myArray:
if minNum > element:
minNum = element
Update my code to
for index in range(0, int(len(myArray)/2)+1):
if minNum > myArray[index]:
minNum = myArray[index]
if minNum > myArray[- index - 1]:
minNum = myArray[- index - 1]
Is there is any reason why they used n iteration
Upvotes: 0
Views: 226
Reputation: 3825
Your code has a small overhead and is actually slower than the article code.
I have made a small program that compares the execution time for both
Check this.
Explanation:
In the legacy style,
The loop runs for n times and make 1 comparison every time. Thus abruptly speaking, it takes, O(n) time. In your code the loop runs for around n/2 times and makes 2 comparisons every time plus the overhead of initializing the
lastElement
Thus although both take around O(n) times but the solution OP provides should run slower in most cases
OP's answer could run faster in the case when the degree of sorting is high. Processing sorted arrays is much faster.
Upvotes: 3