Skip to content

Instantly share code, notes, and snippets.

@kaminomisosiru
Created June 30, 2017 06:45
Show Gist options
  • Save kaminomisosiru/dd5d19455944f62727c6a71df887e830 to your computer and use it in GitHub Desktop.
Save kaminomisosiru/dd5d19455944f62727c6a71df887e830 to your computer and use it in GitHub Desktop.
binary search and randomizes quick sort
# -*- coding: utf-8 -*-
import math
import random
def quick_sort(arr):
l = len(arr)
if l < 1:
return arr
pivot = arr[random.randrange(0,l)]
smaller = [arr[i] for i in range(l) if arr[i] < pivot]
larger = [arr[i] for i in range(l) if arr[i] > pivot]
return quick_sort(smaller) + [pivot] + quick_sort(larger)
def binary_search(arr, target):
length = len(arr)
i = 0
j = length-1
while i <= j:
k = math.floor((i+j)/2)
if target < arr[k]:
j = k-1
elif target > arr[k]:
i = k+1
else:
print('Found:',target)
return k
print('Not found')
return False
arr = [0,5,4,7,8,2,3,9,1,6]
arr = quick_sort(arr)
binary_search(arr, 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment