diff --git a/src/iterative_sorting/iterative_sorting.py b/src/iterative_sorting/iterative_sorting.py index e27496b3..082ffb58 100644 --- a/src/iterative_sorting/iterative_sorting.py +++ b/src/iterative_sorting/iterative_sorting.py @@ -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 ): diff --git a/src/recursive_sorting/recursive_sorting.py b/src/recursive_sorting/recursive_sorting.py index dcbf3757..589af93f 100644 --- a/src/recursive_sorting/recursive_sorting.py +++ b/src/recursive_sorting/recursive_sorting.py @@ -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