diff --git a/src/iterative_sorting/iterative_sorting.py b/src/iterative_sorting/iterative_sorting.py index e27496b3..ae396182 100644 --- a/src/iterative_sorting/iterative_sorting.py +++ b/src/iterative_sorting/iterative_sorting.py @@ -1,28 +1,45 @@ # TO-DO: Complete the selection_sort() function below + +arr = [5, 3, 10, 2, 1] def selection_sort( arr ): # loop through n-1 elements for i in range(0, len(arr) - 1): cur_index = i 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 = cur_index + smallest_index = j + print(j) - - - # TO-DO: swap - - - + arr[smallest_index], arr[cur_index] = arr[cur_index], arr[smallest_index] return arr +"""print(selection_sort( arr ))""" # TO-DO: implement the Bubble Sort function below +lizzy = [5, 3, 10, 2, 1, 0, 12, 89, 2, 90] def bubble_sort( arr ): + swapped = True + while swapped: + swapped = False + for j in range(len(arr) -1): + check = j + 1 + if arr[j] > arr[check]: + swapped = True + arr[j], arr[check] = arr[check], arr[j] + + print("ARRR", arr) + + return arr - +print(bubble_sort(lizzy)) # STRETCH: implement the Count Sort function below def count_sort( arr, maximum=-1 ): diff --git a/src/recursive_sorting/recursive_sorting.py b/src/recursive_sorting/recursive_sorting.py index dcbf3757..4e02d315 100644 --- a/src/recursive_sorting/recursive_sorting.py +++ b/src/recursive_sorting/recursive_sorting.py @@ -1,18 +1,43 @@ # TO-DO: complete the helpe function below to merge 2 sorted arrays + +arrA = [1, 5, 7, 15] +arrB = [3, 8, 10] def merge( arrA, arrB ): elements = len( arrA ) + len( arrB ) merged_arr = [0] * elements # TO-DO + a = b = 0 + for i in range(0, elements): + if a >= len(arrA): + 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 return merged_arr + +print(merge(arrA, arrB )) - +arr = [6,4,99,5,2,87,90, 3, 7, 32, 54, 55] # TO-DO: implement the Merge Sort function below USING RECURSION def merge_sort( arr ): # TO-DO - - return arr - + if len(arr) <= 1: + return arr + left = arr[:len(arr)// 2] + right = arr[len(arr)// 2 :] + left = merge_sort(left) + right = merge_sort(right) + return merge(left, right) + +print(merge_sort( arr )) # STRETCH: implement an in-place merge sort algorithm def merge_in_place(arr, start, mid, end): @@ -31,3 +56,6 @@ def merge_sort_in_place(arr, l, r): def timsort( arr ): return arr + +# TO-DO: implement the Merge Sort function below USING RECURSION + diff --git a/src/test/test.py b/src/test/test.py new file mode 100644 index 00000000..3981d1e1 --- /dev/null +++ b/src/test/test.py @@ -0,0 +1,5 @@ + + +arr = ['Joe', 2, 'Ted', 4.98, 14, 'Sam', 'void *', '42', 'float', 'pointers', 5006] +for i in range(len(arr)): + print(arr[i])