zoukankan      html  css  js  c++  java
  • 二分查找(算法)(原创)

     #给定一个有序数组和目标值,查找目标值出现在给定数组中的区间范围,复杂度要求为O(log n),若无目标区间值则区间为[-1,-1] 

    1
    # -*- coding: utf-8 -*- 2 """ 3 Created on Tue Oct 10 09:04:53 2017 4 5 @author: nvidia 6 """ 7 8 #!/usr/bin/python 9 #coding=utf-8 10 #自定义函数,实现二分查找,并返回查找结果 11 def binary_search(find, foo) : 12 low = 0 13 high = len(foo) 14 while low <= high : 15 mid = (low + high) / 2 16 if foo[mid] == find : 17 return mid 18 #左半边 19 elif foo[mid] > find : 20 high = mid -1 21 #右半边 22 else : 23 low = mid + 1 24 #未找到返回-1 25 return -1 26 foo = [1,3,3,4,4,8,11,18] 27 #进行二分查找算法前必须保证要查找的序列时有序的,这里是升序列表 28 foo.sort() 29 print "原有序列表为:",foo 30 try : 31 find = int(raw_input("请输入要查找的数:")) 32 except : 33 print "请输入正整数!" 34 exit() 35 result = binary_search(find, foo) 36 if result != -1 : 37 if result == 0: 38 print "[%d,%d]" %(foo[0],foo[1]) 39 #考虑到查找值序号为0时,前置数值没有的情况 40 else : 41 print "[%d,%d]" %(foo[result-1],foo[result]) 42 #正常查找值情况 43 44 else : 45 print "[-1,-1]" 46 #无查找值情况 47 48 """ 49 the down words are the result. 50 system:ubuntu Jetson TX2 51 52 Python 2.7.12 (default, Nov 19 2016, 06:48:10) 53 Type "copyright", "credits" or "license" for more information. 54 55 IPython 2.4.1 -- An enhanced Interactive Python. 56 ? -> Introduction and overview of IPython's features. 57 %quickref -> Quick reference. 58 help -> Python's own help system. 59 object? -> Details about 'object', use 'object??' for extra details. 60 %guiref -> A brief reference about the graphical user interface. 61 62 In [1]: runfile('/home/nvidia/Documents/work/20171010.py', wdir='/home/nvidia/Documents/work') 63 原有序列表为: [1, 3, 3, 4, 4, 8, 11, 18] 64 65 请输入要查找的数:4 66 [4,4] 67 68 In [2]: runfile('/home/nvidia/Documents/work/20171010.py', wdir='/home/nvidia/Documents/work') 69 原有序列表为: [1, 3, 3, 4, 4, 8, 11, 18] 70 71 请输入要查找的数:8 72 [4,8] 73 74 In [3]: runfile('/home/nvidia/Documents/work/20171010.py', wdir='/home/nvidia/Documents/work') 75 原有序列表为: [1, 3, 3, 4, 4, 8, 11, 18] 76 77 请输入要查找的数:10 78 [-1,-1] 79 80 """





     
    探究未知是最大乐趣
  • 相关阅读:
    hdu 1518 square
    AWR报告的使用
    状态模式之观察者和状态模式
    Arduino笔记五三轴陀螺仪L3G4200D
    TCP IP 学习笔记 二 链路层
    机房收费系统数据库设计小结
    TMSSCRIPTER介绍
    TMSScripter语法
    listview的一些用法
    进制转换
  • 原文地址:https://www.cnblogs.com/Mufasa/p/7647377.html
Copyright © 2011-2022 走看看