转载:https://blog.csdn.net/qq_24629159/article/details/88630655
读者可以自行修改数组元素进行多次测试,亲测可用
查找最左目标值
/*
查找最左目标值
*/
/*
非递归的二分查找
arrat:数组 , n:数组最大下标值; target:查找的数据; 返回target所在数组的下标
*/
#include<iostream>
#include <windows.h>
using namespace std;
int found(int arr[], int n, int target){
int low = 0;
int high = n;
while(low < high){
int mid = (low + high)/2;//4,7,6,5
if(arr[mid] >= target){
high = mid;//[5,7],[5,6]
}
else{
low = mid + 1; //[5,9],[6,6]
}
}
if(arr[high] == target){
return high;
}
return -1;
}
int main(){
int a[100]={22,33,33,57,67,89,89,99,99,99};//middle依次为a[4]=12,a[7]=15(第二个),a[8]=29(第一个)
int n=9;
int k;
SetConsoleOutputCP(65001);
printf("请输入要查找对应下标的数组元素:\n");
cin>>k;//输入要找的数字c语言把cin换为scanf即可
cout<<found(a,n,k);
return 0;
}
输出:
查找最右目标值
/*
查找最右目标值
*/
/*
非递归的二分查找
arrat:数组 , n:数组最大下标值; target:查找的数据; 返回target所在数组的下标
*/
#include<iostream>
#include <windows.h>
using namespace std;
int found(int arr[], int n, int target){
int low = 0;
int high = n;
while(low < high){
int mid = (low + high)/2+1;
if(arr[mid] <= target){
low = mid;
}
else{
high = mid - 1;
}
}
if(arr[high] == target){
return high;
}
return -1;
}
int main(){
int a[100]={22,33,33,57,67,89,89,99,99,99};//middle依次为a[4]=12,a[7]=15(第二个),a[8]=29(第一个)
int n=9;
int k;
SetConsoleOutputCP(65001);
cout<<"请输入要查找对应下标的数组元素:"<<endl;
cin>>k;//输入要找的数字c语言把cin换为scanf即可
cout<<found(a,n,k);
return 0;
}
输出: