【问题标题】:Why is one linear-search giving me a different output than the other?为什么一个线性搜索给我的输出与另一个不同?
【发布时间】:2016-06-24 01:52:54
【问题描述】:

我正在转换算法解锁书中提供的伪代码。

第一个伪代码如下:

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");

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

【问题讨论】:

    标签: javascript arrays algorithm search


    【解决方案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
        }
      }
    

    【讨论】:

    • 谢谢。更有意义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    • 2021-02-20
    • 2023-04-08
    • 2020-07-07
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    相关资源
    最近更新 更多