In the 9th chapter of the Code Tuning section of programming Zhu Ji Nanxiong, there's a little tip. The author talks about the optimization problem of the loop in sequential search, the source code is as follows:
<span style= "FONT-SIZE:18PX;" >int Search () {for
(int i=0;i<n;i++) {
if (x[i]==t)
return i;
return-1;
}
}
</span>
The loop is already very concise, but it can be a little more streamlined.
There are two kinds of tests in the inner loop: the first Test checks if I have reached the end of the array, and the second Test verifies that X[i] is the desired element. As long as you place a sentinel value at the end of the array, you can replace the first test with the second one.
<span style= "FONT-SIZE:18PX;" >int Search2 () {
int hold = X[n], x[n] = t;
for (int i=0;; i++) {
if (x[i] = = t) break
;
}
X[n] = hold;
if (i = = n)
return-1;
else
return i;
}
</span>
In the article, the author mentions that this improvement has led to a 5% speedup in the overall program's running time.