二分查找(binarySearch)

本文详细介绍了快速排序算法的实现过程,并通过一个具体的示例进行演示。同时,文章还探讨了两种二分查找算法的实现方式:递归与非递归。此外,文章还展示了如何使用C++标准模板库(STL)对数组进行排序。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void QSort(int a[], int low, int high)
{
if(low>=high) //关于这个终止条件, 在下边处理后,low可能会大于或等于high
{
return;
}
int first = low;
int last = high;
int key = a[first]; //use the first elements to be the key
while(first<last)
{

while(first<last&&a[last]>=key)
{
last--;
}
a[first] = a[last];
while(first<last&&a[first]<=key)
{
first++;
}
a[last] = a[first];
a[first] = key;
QSort(a, low, first-1);
QSort(a, first+1, high);

}

}


int NBinarySearch(vector<int> arr, int n, int target)
{
int low = 0, high = n - 1; //"low" is the low limit of search, "high" is the high limit of search
while(low<=high)
{
int middle = (low + high) / 2;
if(arr[middle]==target)
{
return middle;
}
else if(arr[middle]>target)
{
high = middle - 1;
}
else
{
low = middle + 1;
}
}

return -1; //the target is not in the array
}


int BinarySearch(vector<int> arr, int target, int low, int high)
{
if(low>high) return -1; //recursive termination conditions are always a problem that needs to be explored,when low and high are equal, if the target value can not be found, this means the target value doesn't exist
int middle = (low + high) / 2; //determines whethers the target values is equals to the value of "middle" position
if(target==arr[middle])
{
return middle;
}
else if(target>arr[middle])
{
return BinarySearch(arr, target, middle+1, high);
}
else
{
return BinarySearch(arr, target, low, middle-1);
}
}

bool com(int &a, int &b)  //this is the parameter of sort 
{
return a < b;
}
int main()
{
int a[] = {57, 68, 59, 52, 72, 28, 96, 33, 24};
vector<int> arr(a, a+9);
vector<int>::iterator iter = arr.begin();

sort(arr.begin(), arr.end(), com);
for(; iter!=arr.end(); iter++)
cout << *iter << " ";
cout << endl;

int result = NBinarySearch(arr, 9, 52);
cout << "the result of none_recurrence method: " << result << endl;
result = BinarySearch(arr, 52, 0, 8);
cout << "the result of recurrence method: " << result << endl;
return 0;
}

 

 

转载于:https://www.cnblogs.com/1915884031A-qqcom/p/7588353.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值