Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 30 additions & 4 deletions project/iterative_sorting.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,16 @@ def selection_sort( arr ):
smallest_index = cur_index
# TO-DO: find next smallest element
# (hint, can do in 3 loc)

for j in range(cur_index, len(arr)):
if arr[j] < arr[smallest_index]:
smallest_index = j



# TO-DO: swap

temp = arr[smallest_index]
arr[smallest_index] = arr[cur_index]
arr[cur_index] = temp



Expand All @@ -20,17 +24,39 @@ def selection_sort( arr ):

# TO-DO: implement the Insertion Sort function below
def insertion_sort( arr ):

for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
return arr


# STRETCH: implement the Bubble Sort function below
def bubble_sort( arr ):

for passnum in range(len(arr)-1,0,-1):
for i in range(passnum):
if arr[i]>arr[i+1]:
temp = arr[i]
arr[i] = arr[i+1]
arr[i+1] = temp
return arr


# STRETCH: implement the Count Sort function below
def count_sort( arr, maximum=-1 ):
m = maximum + 1
count = [0] * maximum

for a in arr:
count[a] = count[a] + 1
i = 0
for a in range(m):
for c in range(count[a]):
arr[i] = a
i = i + 1


return arr
14 changes: 14 additions & 0 deletions project/searching.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,34 @@
def linear_search(arr, target):

# TO-DO: add missing code
for i in range(len(arr)):
if arr[i] == target:
return i

return -1 # not found


# STRETCH: write an iterative implementation of Binary Search
def binary_search(arr, target):


if len(arr) == 0:
return -1 # array empty

low = 0
high = len(arr)-1

# TO-DO: add missing code
low = 0
high = len(arr) - 1
while low <= high:
mid - low + (high - low) // 2
mid_val = arr[mid]
if mid_val == target:
return mid
elif mid_val < value:
low = mid + 1
else: high = mid - 1

return -1 # not found

Expand Down
14 changes: 7 additions & 7 deletions project/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,14 @@ def test_insertion(self):
self.assertEqual(insertion_sort(arr3), [0,1,2,3,4,5])


# def test_bubble(self):
# arr1 = [1, 5, 8, 4, 2, 9, 6, 0, 3, 7]
# arr2 = []
# arr3 = [0, 1, 2, 3, 4, 5]
def test_bubble(self):
arr1 = [1, 5, 8, 4, 2, 9, 6, 0, 3, 7]
arr2 = []
arr3 = [0, 1, 2, 3, 4, 5]

# self.assertEqual(bubble_sort(arr1), [0,1,2,3,4,5,6,7,8,9])
# self.assertEqual(bubble_sort(arr2), [])
# self.assertEqual(bubble_sort(arr3), [0,1,2,3,4,5])
self.assertEqual(bubble_sort(arr1), [0,1,2,3,4,5,6,7,8,9])
self.assertEqual(bubble_sort(arr2), [])
self.assertEqual(bubble_sort(arr3), [0,1,2,3,4,5])


# def test_count(self):
Expand Down