Advertisement
Guest User

Untitled

a guest
Jul 1st, 2016
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. # coding=utf-8
  2. """
  3. bisect实现源码就是**二分查找算法**,**二分查找的对象是:有序数组。这点特别需要注意。要先把数组排好序再操作。**
  4.  
  5. **基本步骤:**
  6.  
  7. - 从数组的中间元素开始,如果中间元素正好是要查找的元素,则搜素过程结束;
  8. - 如果某一特定元素大于或者小于中间元素,则在数组大于或小于中间元素的那一半中查找,而且跟开始一样从中间元素开始比较。
  9. - 如果在某一步骤数组为空,则代表找不到。
  10.  
  11. 这种搜索算法每一次比较都使搜索范围缩小一半。时间复杂度:**O(logn)**
  12.  
  13. 如下源码分析:
  14.  
  15. :copyright: (c) 2016 by fangpeng(@beginman.cn).
  16. :license: MIT, see LICENSE for more details.
  17. """
  18.  
  19.  
  20. def insort_right(a, x, lo=0, hi=None):
  21. """在a列表中插入元素x,且保持排序(假设a已经排过序).
  22.  
  23. 如果x已经在a中,那么插入到最右边的x的右边.
  24. 可选参数`lo` (默认 0) and `hi` (默认 `len(a)`列表总长度) 绑定搜索的切片。
  25. """
  26.  
  27. if lo < 0:
  28. raise ValueError('lo must be non-negative')
  29. if hi is None:
  30. hi = len(a)
  31. while lo < hi:
  32. mid = (lo+hi)//2 # 取list中间位置
  33. if x < a[mid]: # 如果x 小于list中间的值,则在前半段继续查找
  34. hi = mid # hi=mid 将总长度缩短到中间
  35. else: # 如果x 大于list中间的值,则在后半段继续查找
  36. lo = mid+1 # lo = mid+1, 起始位置就从中间位置+1处(也就是后半段)开始
  37. a.insert(lo, x)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement