"Sentinel" technique in linear search

What is linear search

The basic process of linear search is to compare several data from beginning to end one by one until the target data is found.

example

Suppose there are 50 boxes, each of which contains a piece of paper with any number written on it, and the boxes are marked with serial numbers from 1 to 50. Now we need to find out whether there is a box with a note with the number to find from the 50 boxes.
Suppose our data is as follows, the number we want to find is 8254

  1 => 1952,2 => 4028,3 => 99,4 => 7161,5 => 6357,
  6 => 9293,7 => 5017,8 => 6575,9 => 2590,10 => 2706,
  11 => 5107,12 => 7203,13 => 8907,14 => 7706,15 => 2209,
  16 => 671,17 => 272,18 => 1344,19 => 7099,20 => 1987,
  21 => 6023,22 => 1012,23 => 8013,24 => 6103, 25 => 8069,
  26 => 5694,27 => 6331,28 => 2781,29 => 6285,30 => 5223,
  31 => 8812,32 => 5056,33 => 4515,34 => 3554,35 => 9074,
  36 => 362,37 => 2131,38 => 8970,39 => 8783,40 => 5911,
  41 => 2248,42 => 6953,43 => 6827,44 => 7359,45 => 7217,
  46 => 4911,47 => 3978,48 => 9985,49 => 7970,50 => 7320
)

Implementation without sentinels (php version)

$num = 8254;
while(true){
    if($i>50){  // 判断箱子的编号
        echo 'not found';
        exit;
    }
    if($arr[$i]!=$num){ // 判断数字
        $i++;
    }else{
        echo 'the number '.$num.' is in the box '.$i;
        exit;
    }
}

If the sentinel is not used, we have to determine whether the number of the box is greater than 50 each time, and determine whether the current number is the number we are looking for.

Implementation of using sentinel (php version)

Judging the box number every time is obviously a waste. In order to avoid this unnecessary judgment, we added box No. 51 and put the number we were looking for in it. This kind of data is called "sentinel".

$num = 8254;
$guard = 51;
$arr[$guard] = $num;
while(true){
    if($arr[$i]!=$num){
        $i++;
    }else{
        if($i!=$guard){
            echo 'the number '.$num.' is in the box '.$i;
        }else{
            echo 'not found';
        }
        exit;
    }
}

After using the sentry, we don't have to judge the box number every time.

Guess you like

Origin blog.csdn.net/wang740209668/article/details/107627270