为什么一个线性搜索给出了与另一个不同的输出?

时间:2016-06-24 01:52:55

标签: javascript arrays algorithm search

我正在转换Algorithms Unlocked book中提供的伪代码。

第一个伪代码如下:

Procedure LINEAR-SEARCH (A; n; x)
Inputs:
   A: an array.
   n: the number of elements in A to search through.
   x: the value being searched for.
Output: Either an index i for which A[i] = x, or the special value NOT-FOUND, which could be any invalid index into the array, such as 0 or any negative integer.
1. Set answer to NOT-FOUND.
2. For each index i, going from 1 to n, in order:
   A. If A[i] = x, then set answer to the value of i. 
3. Return the value of answer as the output.

以下是在Javascript中解决此伪代码的一个版本:

版本1:输出:将i返回为5

function linearSearch(data, searchQuery) {
  var answer = 'not found';
  for (var i = 0, len = data.length; i < len; i++) {
    if (data[i] === searchQuery) {
      answer = i;
    }
  }
  return answer;
}

var names = ["Jack", "Molly", "Tristan", "Jacob", "Jacob", "Jacob", "Steph"]
var result = linearSearch(names, "Jacob");
console.log(result);

这是另一个:

版本2:输出:将i返回为3

var answer = 'not found';

function LinearSearch(A,n,searchQuery) {
  var answer = 'not found';
  for (var i = 0; i < A.length; i++) {
    if (A[i] === searchQuery) {
      return i;
    }
  }
  return answer;
}

var names = ["Jack", "Molly", "Tristan", "Jacob", "Jacob", "Jacob", "Steph"];
var result = LinearSearch(names, names.length, "Jacob");

我在代码中做了什么来实现两种不同的输出?

1 个答案:

答案 0 :(得分:1)

第一个函数在找到匹配项后不会立即退出循环,但第二个函数不会。

在第一个问题中,当i345时,本地answer变量将设置为i }。最后一个值是5,这就是返回的内容。

for (var i = 0, len = data.length; i < len; i++) {
  if (data[i] === searchQuery) {
    answer = i; // update answer - LOOP CONTINUES
  }
}

在第二个中,一旦找到匹配,函数就会返回该索引:

  for (var i = 0; i < A.length; i++) {
    if (A[i] === searchQuery) {
      return i; // return index immediately and stop iterating
    }
  }