欢迎来到入门教程网!

C语言

当前位置:主页 > 软件编程 > C语言 >

C++实现旋转数组的二分查找

来源:本站原创|时间:2020-01-10|栏目:C语言|点击:

本文实例讲述了C++实现旋转数组的二分查找方法,分享给大家供大家参考。具体方法如下:

题目要求:

旋转数组,如{3, 4, 5, 1, 2}是{1, 2, 3, 4, 5}的一个旋转,要求利用二分查找查找里面的数。

这是一道很有意思的题目,容易考虑不周全。这里给出如下解决方法:

#include <iostream>

using namespace std;

int sequentialSearch(int *array, int size, int destValue)
{
 int pos = -1;
 if (array == NULL || size <= 0)
 return pos;

 for (int i = 0; i < size; i++)
 {
 if (array[i] == destValue)
 {
  pos = i;
  break;
 }
 }

 return pos;
}

int normalBinarySearch(int *array, int leftPos, int rightPos, int destValue)
{
 int destPos = -1;
 if (array == NULL || leftPos < 0 || rightPos < 0)
 {
 return destPos;
 }

 int left = leftPos;
 int right = rightPos;

 while (left <= right)
 {
 int mid = (right - left) / 2 + left;

 if (array[mid] == destValue)
 {
  destPos = mid;
  break;
 }
 else
  if (array[mid] < destValue)
  {
  left = mid + 1;
  }
  else
  {
  right = mid - 1;
  }
 }

 return destPos;
}

int rotateBinarySearch(int *array, int size, int destValue)
{
 int destPos = -1;
 if (array == NULL || size <= 0)
 {
 return destPos;
 }

 int leftPos = 0;
 int rightPos = size - 1;

 while (leftPos <= rightPos)
 {
 if (array[leftPos] < array[rightPos])
 {
  destPos = normalBinarySearch(array, leftPos, rightPos, destValue);
  break;
 }
 
 int midPos = (rightPos - leftPos) / 2 + leftPos;
 if (array[leftPos] == array[midPos] && array[midPos] == array[rightPos])
 {
  destPos = sequentialSearch(array, size, destValue);
  break;
 }
 if (array[midPos] == destValue)
 {
  destPos = midPos;
  break;
 }

 if (array[midPos] >= array[leftPos])
 {
  if (destValue >= array[leftPos])
  {
  destPos = normalBinarySearch(array, leftPos, midPos - 1, destValue);
  break;
  } 
  else
  {
  leftPos = midPos + 1;
  }
 }
 else
 {
  if (array[midPos] <= array[rightPos])
  {
  destPos = normalBinarySearch(array, midPos + 1, rightPos, destValue);
  break;
  } 
  else
  {
  rightPos = midPos - 1;
  }
 }
 }

 return destPos;
}

int main()
{
 //int array[] = {3, 4, 5, 1, 2};
 //int array[] = {1, 2, 3, 4, 5};
 //int array[] = {1, 0, 1, 1, 1};
 //int array[] = {1, 1, 1, 0, 1};
 //int array[] = {1};
 //int array[] = {1, 2};
 int array[] = {2, 1};
 const int size = sizeof array / sizeof *array;

 for (int i = 0; i <= size; i++)
 {
 int pos = rotateBinarySearch(array, size, array[i]);
 cout << "find " << array[i] << " at: " << pos + 1 << endl;
 }

 for (int i = size; i >= 0; i--)
 {
 int pos = rotateBinarySearch(array, size, array[i]);
 cout << "find " << array[i] << " at: " << pos + 1 << endl;
 }
}

希望本文所述对大家C++算法设计的学习有所帮助。

上一篇:在Visual Studio中用C++语言创建DLL动态链接库图文教程

栏    目:C语言

下一篇:C语言实现socket简单通信实例

本文标题:C++实现旋转数组的二分查找

本文地址:https://www.xiuzhanwang.com/a1/Cyuyan/3335.html

网页制作CMS教程网络编程软件编程脚本语言数据库服务器

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:835971066 | 邮箱:835971066#qq.com(#换成@)

Copyright © 2002-2020 脚本教程网 版权所有