Skip to content

Commit 9b4c8df

Browse files
author
Mia von Steinkirch
committed
add some exs
1 parent 0d5e21b commit 9b4c8df

File tree

7 files changed

+85
-1
lines changed

7 files changed

+85
-1
lines changed

interview_cake/binary_search.py

Lines changed: 0 additions & 1 deletion
This file was deleted.
File renamed without changes.
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#!/usr/bin/env python
2+
3+
4+
def binary_search(array, value):
5+
last, first = len(array), 0
6+
7+
while first < last:
8+
mid = (last - first)//2
9+
item = array[mid]
10+
11+
if item == value:
12+
return True
13+
14+
elif item < value:
15+
last = mid
16+
17+
else:
18+
first = mid
19+
20+
return False
21+
22+
def binary_search_rec(array, value, first=0, last=None):
23+
last = last or len(array)
24+
if len(array[first:last]) < 1:
25+
return False
26+
27+
mid = (last - first)//2
28+
if array[mid] == value:
29+
return True
30+
elif array[mid] < value:
31+
return binary_search_rec(array, value, first=first, last=mid)
32+
else:
33+
return binary_search_rec(array, value, first=mid, last=last)
34+
35+
36+
array = [3, 4, 6, 7, 10, 11, 34, 67, 84]
37+
value = 6
38+
assert(binary_search(array, value) == True)
39+
assert(binary_search_rec(array, value) == True)
40+
value = 8
41+
assert(binary_search(array, value) == False)
42+
assert(binary_search_rec(array, value) == False)
43+
array = [8]
44+
assert(binary_search(array, value) == True)
45+
assert(binary_search_rec(array, value) == True)
46+
array = []
47+
assert(binary_search(array, value) == False)
48+
assert(binary_search_rec(array, value) == False)
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#!/usr/bin/env python
2+
3+
def merge_sort(list_to_sort):
4+
# Base case: lists with fewer than 2 elements are sorted
5+
if len(list_to_sort) < 2:
6+
return list_to_sort
7+
8+
# Step 1: divide the list in half
9+
mid_index = len(list_to_sort) / 2
10+
left = list_to_sort[:mid_index]
11+
right = list_to_sort[mid_index:]
12+
13+
# Step 2: sort each half
14+
sorted_left = merge_sort(left)
15+
sorted_right = merge_sort(right)
16+
17+
# Step 3: merge the sorted halves
18+
sorted_list = []
19+
current_index_left = 0
20+
current_index_right = 0
21+
22+
while len(sorted_list) < len(left) + len(right):
23+
if ((current_index_left < len(left)) and
24+
(current_index_right == len(right) or
25+
sorted_left[current_index_left] < sorted_right[current_index_right])):
26+
sorted_list.append(sorted_left[current_index_left])
27+
current_index_left += 1
28+
else:
29+
sorted_list.append(sorted_right[current_index_right])
30+
current_index_right += 1
31+
return sorted_list
32+
33+
34+
35+
list_to_sort = [5, 3, 7, 12, 1, 0, 10]
36+
37+
print merge_sort(list_to_sort)
File renamed without changes.
File renamed without changes.

0 commit comments

Comments
 (0)