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
36 changes: 33 additions & 3 deletions src/iterative_sorting/iterative_sorting.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,55 @@ def selection_sort( arr ):
cur_index = i
smallest_index = cur_index
# TO-DO: find next smallest element
# (hint, can do in 3 loc)

# (hint, can do in 3 loc)

# b. Iterate to the left until you find the correct index in the "sorted" part of the array at which this element should be inserted
# - Shift items over to the right as you iterate

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

# c. When the correct index is found, copy temp into this position
# TO-DO: swap


arr[smallest_index], arr[cur_index] = arr[cur_index], arr[smallest_index]


return arr






# TO-DO: implement the Bubble Sort function below
def bubble_sort( arr ):

# make flag to show if swap has occured
swaps_occured = True
# Run until no swaps
while swaps_occured:
swaps_occured = False

#for each element in the array...
for i in range(len(arr) - 1):

# check neighbor to the right
if arr[i] > arr[i+1]:

# if neighbor is smaller, swap and make flag true
arr[i], arr[i+1] = arr[i+1], arr[i]
swaps_occured = True

return arr







# STRETCH: implement the Count Sort function below
def count_sort( arr, maximum=-1 ):

Expand Down
42 changes: 41 additions & 1 deletion src/recursive_sorting/recursive_sorting.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,57 @@
# TO-DO: complete the helpe function below to merge 2 sorted arrays
# a = [1,3,5]
# b = [2,4,6]
# merged_arr= [1, 2, 0, 0, 0, 0]
def merge( arrA, arrB ):
elements = len( arrA ) + len( arrB )
merged_arr = [0] * elements
# TO-DO

#initialize pointers to first element of both arrays
a = 0 # these are indexes
b = 0
#compare arr[0] of arrA and arrB
for i in range(elements):
if a >= len(arrA):
print(i)
merged_arr[i] = arrB[b]
b += 1
elif b >= len(arrB):
merged_arr[i] = arrA[a]
a += 1
elif arrA[a] < arrB[b]:
merged_arr[i] = arrA[a]
a += 1
else:
merged_arr[i] = arrB[b]
b += 1


#copy the smallest to merged_arr

return merged_arr




# TO-DO: implement the Merge Sort function below USING RECURSION
def merge_sort( arr ):
# TO-DO
# base case - if len(arr) == 1, return arr
if len(arr) <= 1:
return arr

return arr
#split arr in half
left = arr[:len(arr) // 2]
right = arr[len(arr) // 2:] #trouble understanding this slice

#sort each half
left = merge_sort(left)
right = merge_sort(right)

#merge them back together
#return arr
return merge(left, right)


# STRETCH: implement an in-place merge sort algorithm
Expand Down