二分搜
Binary Search
找資料的思考邏輯
找資料的思考邏輯
如果我們今天要來玩猜數字......
遊戲規則:
關主想一個數字作為謎底
其他人要在範圍內猜到這個數字
先猜出來的人為勝者
怎麼猜最有效率?
10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 100 |
---|
關主:大於50
切一半!
10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 100 |
---|
關主:大於75
10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 100 |
---|
關主:大於87
10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 100 |
---|
關主:大於94
10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 100 |
---|
關主:猜對了!是97!
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n=99;
int first=0,last=100,mid;
while(first<=last)
{
mid=(first+last)/2;
if(mid<n)
first=mid+1;
else if(mid>n)
last=mid-1;
else if(mid==n)
{
cout<<n;
break;
}
}
}
排序過的資料才能使用二分搜!
10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 100 |
---|
first
mid
last
10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 100 |
---|
first
mid
last
10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 100 |
---|
first
mid
last
不同寫法
迴圈寫法
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n=97;
int first=0,last=100,mid;
while(first<=last)
{
mid=(first+last)/2;
if(mid<n)
first=mid+1;
else if(mid>n)
last=mid-1;
else if(mid==n)
{
cout<<n;
break;
}
}
}
遞迴寫法
int main()
{
int a[100];
int n=97;
for(int i=0;i<100;i++)
a[i]=i;
int first=0,last=100,mid;
int index=bs(a,first,last,n);
cout<<index;
return 0;
}
#include<bits/stdc++.h>
using namespace std;
int bs(int a[],int first,int last,int n)
{
while(first<=last)
{
int mid=(first+last)/2;
if(a[mid]==n)
return mid;
else if(n<a[mid])
return bs(a,first,mid-1,n);
else
return bs(a,mid+1,last,n);
}
}
TRY TRY SEE
NO KAHOOT!
Binary Search
By ㄌㄌ
Binary Search
- 88