diff --git a/src/iterative_sorting/iterative_sorting.py b/src/iterative_sorting/iterative_sorting.py index e27496b3..a7b250a0 100644 --- a/src/iterative_sorting/iterative_sorting.py +++ b/src/iterative_sorting/iterative_sorting.py @@ -1,26 +1,31 @@ # TO-DO: Complete the selection_sort() function below -def selection_sort( arr ): +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(i + 1, len(arr)): + if arr[j] < arr[smallest_index]: + smallest_index = j + # TO-DO: swap - - - + if cur_index != smallest_index: + arr[cur_index], arr[smallest_index] = arr[smallest_index], arr[cur_index] return arr # TO-DO: implement the Bubble Sort function below -def bubble_sort( arr ): - +def bubble_sort(arr): + is_swapped = True + while is_swapped: + is_swapped = False + for i in range(len(arr) - 1): + if arr[i] > arr[i + 1]: + arr[i], arr[i + 1] = arr[i + 1], arr[i] + is_swapped = True return arr diff --git a/src/recursive_sorting/recursive_sorting.py b/src/recursive_sorting/recursive_sorting.py index dcbf3757..c82cfb41 100644 --- a/src/recursive_sorting/recursive_sorting.py +++ b/src/recursive_sorting/recursive_sorting.py @@ -3,7 +3,23 @@ def merge( arrA, arrB ): elements = len( arrA ) + len( arrB ) merged_arr = [0] * elements # TO-DO - + + a = 0 + 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 @@ -11,8 +27,15 @@ def merge( arrA, arrB ): def merge_sort( arr ): # TO-DO - return arr + n = len(arr) + if n < 2: + return arr + + mid = n // 2 + arr_l = arr[:mid] + arr_r = arr[mid:] + return merge(merge_sort(arr_l), merge_sort(arr_r)) # STRETCH: implement an in-place merge sort algorithm def merge_in_place(arr, start, mid, end):