康奈尔笔记模板
线索Cues
笔记Notes
  • 编写第一种算法--二分查找
  • 讨论算法的运行时间--O表示法
  • 算法设计方法--递归
  • 听课后复习的思考
  • 图表
 
 
  1. 二分输入必须是有序的,查找的元素如果包含在列表,也返回位置,否则返回null。
  2. logn步就好了
  3. 代码实例   
 
 
 
 
 
 
 

Codes

python
 1 def binary_search(list, item):
 2   # low and high keep track of which part of the list you'll search in.
 3   low = 0
 4   high = len(list) - 1
 5  
 6   # While you haven't narrowed it down to one element ...
 7   while low <= high:
 8     # ... check the middle element
 9     mid = (low + high) // 2
10 我不清楚这里为什么需要两个//,正常不是一个就够了吗,然而我只用一个的时候他提醒我说索引不可以是小数
11     guess = list[mid]
12     # Found the item.
13     if guess == item:
14       return mid
15     # The guess was too high.
16     if guess > item:
17       high = mid - 1
18     # The guess was too low.
19     else:
20       low = mid + 1
21  
22   # Item doesn't exist
23   return None
24  
25 my_list = [1, 3, 5, 7, 9]
26 print(binary_search(my_list, 3)) # => 1
27  
28 # 'None' means nil in Python. We use to indicate that the item wasn't found.
29 print(binary_search(my_list, -1)) # => None

 

 c++
 2 #include<iostream>
 3 using namespace std;
 4  
 5 int binarySearch(int data[],int length,int element)
 6 {
 7     //can only search an array sorted.
 8     int left=0;
 9     int right=length-1;
10     while(right>=left)
11     {
12         int mid=(left+right)/2;
13         int guess=data[mid];
14         if(guess==element)
15             return mid;
16         else if(guess<element)
17             left=mid+1;
18         else
19             right=mid-1;
20     }
21     return -1;
22 }
23  
24 int main()
25 {
26     int arr[]={1,2,5,9,10};
27     int find_ele=0;
28     int length=sizeof(arr)/sizeof(int);
29     cout<<binarySearch(arr,length,find_ele)<<endl;
30     return 0;
31 }

 

  

 c++(错误的办法)
 2  
 3 int search(int arr[],int find)
 4 {
 5 //C++中已明确规定做为参数传递的数组名就是指针,它的大小是该类型的指针大小而非数组大小,所以不能用sizeof来求得大小
 6 //解决方法:我现在还不清楚,
 7 //可以进行操作,就是不可以求大小。
 8     int length=sizeof(arr)/sizeof(int);
 9     return binarySearch(arr,length,find);
10 }
11  
12  
13 int main()
14 {
15     int arr[]={1,2,5,9,10};
16     int find_ele=2;
17     cout<<search(arr,find_ele)<<endl;
18  
19     return 0;
20 }

 

 
 
posted on 2019-09-02 21:34  凭栏听雨客  阅读(189)  评论(0编辑  收藏  举报