def linear_search(L, e):
found = False
for i in range(len(L)):
if e == L[i]:
found = True
return found
linear_search([1,2,6,867,123,99],6)
linear_search([1,2,6,867,123,99],76)
def search(L, e):
for i in range(len(L)):
if L[i] == e:
return True
if L[i] > e:
return False
return False
search([1,2,6,867,1234],6)
search([1,2,6,867,1234],99)
search([1,2,157,6,867,1234,0,17891],0) # list is not sorted hence False
- 1 = n/2^i
- so i= log n
#BISECTION SEARCH IMPLEMENTATION 1
def bisect_search1(L, e):
if L == []:
return False
elif len(L) == 1:
return L[0] == e
else:
half = len(L)//2
if L[half] > e:
return bisect_search1( L[:half], e)
else:
return bisect_search1( L[half:], e)
#BISECTION SEARCH IMPLEMENTATION 2
def bisect_search2(L, e):
def bisect_search_helper(L, e, low, high):
if high == low:
return L[low] == e
mid = (low + high)//2
if L[mid] == e:
return True
elif L[mid] > e:
if low == mid: #nothing left to search
return False
else:
return bisect_search_helper(L, e, low, mid -1)
else:
return bisect_search_helper(L, e, mid + 1, high)
if len(L) == 0:
return False
else:
return bisect_search_helper(L, e, 0, len(L) -1)
Implementation 1 –bisect_search1
Implementation 2 –bisect_search2 and its helper
def bogo_sort(L):
while not is_sorted(L):
random.shuffle(L)
def bubble_sort(L):
swap = False
while not swap:
swap = True
for j in range(1, len(L)):
if L[j-1] > L[j]:
swap = False
temp = L[j]
L[j] = L[j-1]
L[j-1] = temp
O(n^2) where n is len(L)
first step
subsequent step
keep the left portion of the list sorted
def selection_sort(L):
suffixSt= 0
while suffixSt!= len(L):
for i in range(suffixSt, len(L)):
if L[i] < L[suffixSt]:
L[suffixSt], L[i] = L[i], L[suffixSt]
suffixSt+= 1
use a divide-and-conquer approach:
def merge(left, right):
result = []
i,j= 0, 0
while i< len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i+= 1
else:
result.append(right[j])
j += 1
#print(result,'result')
while (i< len(left)):
result.append(left[i])
i+= 1
while (j < len(right)):
result.append(right[j])
j += 1
return result
def merge_sort(L):
if len(L) < 2:
return L[:]
else:
middle = len(L)//2
#print(middle,'middle')
#print(L[:middle],'ll')
#print(L[middle:],'rl')
left = merge_sort(L[:middle])
#print(left,'left')
right = merge_sort(L[middle:])
#print(right,'right')
return merge(left, right)
merge_sort([0,1,5,6,3,7,4])
at first recursion level
at second recursion level
two merges O(n) where n is len(L)
each recursion level is O(n) where n is len(L)
bogosort
bubble sort
selection sort
merge sort
Reference