简体   繁体   English

二进制搜索查找Magic Index

[英]Binary Search for finding Magic Index

I'm practicing binary search and I'm running into a wall when trying to implement it to find the "magic index" in an array. 我正在练习二进制搜索,当我试图实现它以找到数组中的“魔术索引”时,我遇到了问题。 The magic index is A[i] == i . 神奇的指数是A[i] == i

I've found some implementations in Java using recursion , but I'm trying to avoid doing this recursively because recursion is expensive (and I want to see if binary search is appropriate here). 我在Java中发现了一些使用递归的实现 ,但是我试图避免递归这样做,因为递归很昂贵(我想看看二进制搜索是否合适)。

Here is my code: 这是我的代码:

function magicIndex(arr) {
  var result = arr, mid;
  while (result.length > 1) {
    mid = Math.floor(result.length / 2);

    if (result[mid] === mid) {
      return arr.indexOf(result[mid]);
    } else if (mid > result[mid]) {
      result = result.slice(mid+1, result.length);
    } else {
      result = result.slice(0, mid);
    }
  }
  return arr.indexOf(result.pop());
}

The problem is that the algorithm incorrectly slices the array to the wrong side on certain test runs. 问题是算法在某些测试运行时错误地将数组切片到错误的一侧。

For example, [-10, -3, 0, 2, 4, 8] returns 4 , but [-10, 1, 0, 2, 5, 8] returns 4 as well. 例如, [-10, -3, 0, 2, 4, 8]返回4 ,但[-10, 1, 0, 2, 5, 8]返回4

您的第二个数组未排序, 二进制搜索仅适用于已排序的数组。

Since you're practicing, I think it is good for you to code it by yourself but I'll give you a guide. 既然你正在练习,我认为你自己编写代码是件好事,但我会给你一个指导。

Use this algorithm (Note that input array should be sorted already, otherwise implement a sorting method): 使用此算法(请注意,输入数组应该已经排序,否则实现排序方法):

  int arr[n];
  K ← 1; //search key
  l ← 0; r ← n - 1;
  while l ≤ r do
      m ← floor((l + r)/2)
      if K = arr[m]
          return m
      else if K < arr[m]
          r ← m − 1
      else
          l ← m + 1
  return −1

This will output the index of your search key, -1 if key is not found. 这将输出搜索键的索引,如果未找到键,则输出-1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM