Abstract: Binary search or half-interval search
Hunt the index of a number in a given sorted list
The result:
Search 1:
search the index of 2345
0 1999
0 9995
0 999
0 4995
0 499
0 2495
249 499
1245 2495
374 499
1870 2495
436 499
2180 2495
467 499
2335 2495
467 483
2335 2415
467 475
2335 2375
467 471
2335 2355
467 469
2335 2345
The index of 2345 is 469
Search 2:
search the index of 0
0 1999
0 9995
The index of 0 is 0
Search 3:
search the index of 17450000
0 1999
0 9995
17450000 was not in this list
Search 3:
search the index of -24
0 1999
0 9995
-24 was not in this list
Search 4:
search the index of 123
0 1999
0 9995
0 999
0 4995
0 499
0 2495
0 249
0 1245
0 124
0 620
0 62
0 310
0 31
0 155
15 31
75 155
23 31
115 155
23 27
115 135
23 25
115 125
24 25
120 125
123 was not in this list
The script:
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 18 08:39:21 2015
@author: yuan
"""
import math
#hunt the index of a given value using binary search
class search:
def __init__(self, arr):
self.arr=arr
def binary_search(self, start, end, target):
print start, end
#print self.arr[start], self.arr[end]
if target<self.arr[start] or target>self.arr[end]:
return
if target==self.arr[start]:
self.index=start
return
elif target==self.arr[end]:
self.index=end
return
if end-start<=1: #no index found
return
#
mid=int(math.ceil((end-start)/2))+start
#print start, mid, end
if target<=self.arr[mid]:
self.binary_search(start, mid, target)
else:
self.binary_search(mid, end, target)
return
def enter_search(self, target):
#recursive
self.index=-1
print 'search the index of', target
self.binary_search(0, len(self.arr)-1, target)
if self.index>=0:
print 'The index of', self.arr[self.index], 'is', self.index
else:
print target, 'was not in this list'
#main program
arr=range(0,10000, 5)
b=search(arr)
print 'Search 1:'
target=2345
b.enter_search(target)
print 'Search 2:'
target=0
b.enter_search(target)
print 'Search 3:'
target=17450000
b.enter_search(target)
print 'Search 3:'
target=-24
b.enter_search(target)
print 'Search 4:'
target=123
b.enter_search(target)
No comments:
Post a Comment