c - 在循环排序数组中找到最小元素

标签 c algorithm

<分区>

我尝试了以下代码来找出循环排序数组中的最小元素。但是当 low = 1 和 high =2 时它失败了,因为 mid 总是 1 并且 a[mid]=a[1] 总是大于 a[high]。

我在这里尝试使用二进制搜索来找到解决方案。

//finding the minim element in the cyclic sorted array
int arrC[]={10,13,1,3,4,5,8};
int low=0,high =6;
int mid=0,reset =1;
while (low < high)
{
    mid = (low+ high)/2;
    if (arrC[mid]>arrC[high])
    {
        low = mid;
    }
    else if (arrC[mid] < arrC[high])
    {
        high = mid;

    }
}
printf("minimum element is %d",arrC[mid+1]); 

最佳答案

你的代码有两个问题

  • Paulpro 所指...将 arrC[high] 视为无穷大..
  • 除此之外,我还建议您使用

mid = low + (high-low)/2;

不要使用 (low+high)/2 。这可能会导致总和超过整数限制,并导致负值。您的代码可能失败的另一个原因。

关于c - 在循环排序数组中找到最小元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18117350/

相关文章:

c - 显示目录中的文件

algorithm - Saturday Morning Breakfast Cereal 中 FrogSort 的分析是否正确?

algorithm - 生成任意长度的任意字母表的所有组合

algorithm - 如何确定点组

algorithm - 寻词式游戏,分布式字母生成算法

c - AES CTR对称加解密

c - 如何在 Windows 上用 c 中的 ctrl+c 结束 while 循环?

c - 使用 typedef 通过引用传递参数

c - 等级与符号

algorithm - Golang Slice-Java Arraylist-递归回溯-Classic Algo Powerset在Golang中无法按需工作