Programming Zhu Ji Nanxiong---internal loop optimization

Source: Internet
Author: User

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;

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 i;
In the article, the author mentions that this improvement has led to a 5% speedup in the overall program's running time.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.