Application: assume that an out-of-order array needs to query whether an element is in the array. In this case, sequential search is used to traverse the array.
Generally, we will write the following code:
Int sequential_search (int * a, int N, int key) {// The array starts from 1 int I; for (INT I = 1; I <= N; I ++) {if (a [I] = Key) return I;} return 0; // search failed}
Some data structure books use the Sentinel element to change the code like this:
Int sequential_search2 (int * A int N, int key) {int I = 0; A [0] = key; // sentinel I = N; while (A [I]! = Key) {I --;} return I; // If 0 is returned, the query fails}
It seems that there is no difference, but let's look at the running time of my test. The array has 1 billion elements.
Solution. 494 s 3.202 s 3.216 s 3.237 s
Solution. 332 s 2.307 s 2.24 s 2.194 s
Why is solution 2 30% better than solution 1 with the same code ~ Around 40% ???
In the loop, solution 1 has three commands, and solution 2 has two commands. If I <n is missing, the performance of solution 2 has been improved, which is also a wonderful use of the guard element.
The above ideas and code come from page 296 in "big talk Data Structure". I did the test experiment.
The original text of the big data structure, "This search method sets the Sentinel element at the end of the search direction, eliminating the need to determine whether the search location is out of the border after each comparison in the search process, it seems that it is not much different from the original, but it is a very good programming skill because there is a large amount of data and the efficiency is improved significantly. Of course, the "Sentinel" does not necessarily start in the array, or it can end"
My test program:
void main() { int num=1000000000;char *p=new char[num];p[0]=2;char key=p[0];clock_t start, finish; start=clock();if(true){for(int i=1;i<num;i++){if(p[i]==key)break;}}else{int i=num-1;while(p[i]!=key){i--;}}finish=clock();double Total_time = (double)(finish-start) / CLOCKS_PER_SEC; cout<<Total_time<<endl;}