summaryrefslogtreecommitdiffstats
path: root/tools/bsearch.py
diff options
context:
space:
mode:
authorMalfurious <m@lfurio.us>2021-08-03 19:53:26 -0400
committerMalfurious <m@lfurio.us>2021-08-03 19:53:26 -0400
commit5970194d1303e16364ff1405f974c995de46203b (patch)
treed3f748eeb0112205bb7784bd353b22376ee827ae /tools/bsearch.py
parentef6e3a502bf8498a8f641eb3dad11d3065359bbb (diff)
parentaa9da0f6f27759f5f3201bafb0e52f41367f08ef (diff)
downloadlib-des-gnux-5970194d1303e16364ff1405f974c995de46203b.tar.gz
lib-des-gnux-5970194d1303e16364ff1405f974c995de46203b.zip
Merge tag 'pull-duso-imaginary-writeups' of https://github.com/Dusoleil/lib-des-gnux
Writeups and other tools/docs from ImaginaryCTF from Dusoleil. * tag 'pull-duso-imaginary-writeups' of https://github.com/Dusoleil/lib-des-gnux: Adding Initial Commit of the Sploit Tool Adding Various Docs Adding Various Small Tools Git Ignore __pycache__ for All Tools Writeups from Imaginary CTF 2021
Diffstat (limited to '')
-rw-r--r--tools/bsearch.py44
1 files changed, 44 insertions, 0 deletions
diff --git a/tools/bsearch.py b/tools/bsearch.py
new file mode 100644
index 0000000..1c92343
--- /dev/null
+++ b/tools/bsearch.py
@@ -0,0 +1,44 @@
+#binary search
+#searches for an s in i that satisfies x == f(i[s])
+#i = iterable
+#f = function to call on each element of i
+#x = value to search for
+#start = offset into iterable to start
+#end = offset into iterable to end
+#if it finds a match, it returns a tuple of (s,i[s],f(i[s]))
+#if it does not find a match, it returns (-1,None,None)
+def bsearch(i,f,x,start=0,end=-1):
+ if end == -1:
+ end = len(i)-1
+ #s = _bsearch(i,f,start,end,x)
+ s = _bsearch2(i,f,start,end,x)
+ return (s,i[s],f(i[s])) if s != -1 else (s,None,None)
+
+#recursive
+def _bsearch(i,f,lo,hi,x):
+ if hi >= lo:
+ md = (hi+lo)//2
+ a = f(i[md])
+ if a == x:
+ return md
+ elif a > x:
+ return _bsearch(i,f,lo,md-1,x)
+ else:
+ return _bsearch(i,f,md+1,hi,x)
+ else:
+ return -1
+
+#loop
+def _bsearch2(i,f,lo,hi,x):
+ while True:
+ if hi >= lo:
+ md = (hi+lo)//2
+ a = f(i[md])
+ if a == x:
+ return md
+ elif a > x:
+ hi = md-1
+ else:
+ lo = md+1
+ else:
+ return -1