c++ - k 旋转移位数组并找到 x?

标签 c++ algorithm search data-structures binary-search

我们说一个k-rotated-shifted array,这样的数组可以通过k rotate 进行排序。示例是:A=[10, 15, 20, 1, 7]k=2。我提出了一种算法,用于在这个 k-rotated-shifted 数组中找到像 x 这样的键。

谁能帮我验证一下?

enter image description here

编辑 1:我的新代码是:

 int S(int l, int r, int x)
{ int f=A[l], m=A[(l+r)/2], la=A[l];
if (x==f or x==m or x==la)
     return 1;
else {if ((x< f and x>m) || (x>f and x>m) || (x<f and x<m))
   return S((l+r)/2, r, x);
   else
    return S(l,(l+r)/2, x);
}
}

最佳答案

中断在 3,4,5,1,2 中找到 1。中断查找不存在的 key ,因为基本情况仅在找到 key 时触发,从而导致无限循环。

要修复,使用条件

first < middle < x or middle < x < first or x < first < middle.

另请注意,如果我们采用 (i + j)/2 的上限,则与 last 进行比较是多余的。

关于c++ - k 旋转移位数组并找到 x?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29105151/

相关文章:

c++ - 在匿名结构中包装灵活数组时,MSVC 结构布局发生变化?

c++ - 将函数指针成员模板限制为仅派生类

c++ - 如何从 C++ 中的类开始

c++ - 编译基本的 openCV 程序时出错

java - 如何发现 List<Integer> 中缺少的渐进算术数在 Java 8 中是什么?

ios - 快速传递参数?

C - 无法实现微型加密算法(意外值)

python - 使用区间树找出重叠区域

c++ - 解开 Knuth 的结 : how to restructure spaghetti code?

PowerShell 将箭头键绑定(bind)到命令历史搜索