diff --git a/Exercise_1.py b/Exercise_1.py index 3e6adcf4..7823a4a8 100644 --- a/Exercise_1.py +++ b/Exercise_1.py @@ -4,11 +4,19 @@ # It returns location of x in given array arr # if present, else returns -1 def binarySearch(arr, l, r, x): - - #write your code here - - - + + #write your code here + + while l<=r: + m = (l + r)// 2 + if arr[m]>x: + r = m-1 + elif arr[m] 1: + mid = len(arr) // 2 + + # Divide + left = arr[:mid] + right = arr[mid:] + + # Recursively sort both halves + mergeSort(left) + mergeSort(right) + + # Merge the two sorted halves + i = j = k = 0 + + # Compare elements from left and right + while i < len(left) and j < len(right): + if left[i] < right[j]: + arr[k] = left[i] + i += 1 + else: + arr[k] = right[j] + j += 1 + k += 1 + + # Copy remaining elements of left + while i < len(left): + arr[k] = left[i] + i += 1 + k += 1 + + # Copy remaining elements of right + while j < len(right): + arr[k] = right[j] + j += 1 + k += 1 - #write your code here + # Code to print the list def printList(arr): #write your code here - + for x in arr: + print(x, end=" ") + print() + + # driver code to test the above code if __name__ == '__main__': arr = [12, 11, 13, 5, 6, 7] @@ -16,3 +57,6 @@ def printList(arr): mergeSort(arr) print("Sorted array is: ", end="\n") printList(arr) + +# TC - O(nlogn) +# SC - O(n) \ No newline at end of file diff --git a/Exercise_5.py b/Exercise_5.py index 1da24ffb..7e900338 100644 --- a/Exercise_5.py +++ b/Exercise_5.py @@ -2,9 +2,39 @@ # This function is same in both iterative and recursive def partition(arr, l, h): - #write your code here + #write your code here + pivot = arr[h] + i = l + + for j in range(l, h): + if arr[j] <= pivot: + arr[i], arr[j] = arr[j], arr[i] + i += 1 + + arr[i], arr[h] = arr[h], arr[i] + return i def quickSortIterative(arr, l, h): - #write your code here + # write your code here + stack = [(l, h)] + + while stack: + l, h = stack.pop() + + if l >= h: + continue + + p = partition(arr, l, h) + + stack.append((l, p - 1)) + stack.append((p + 1, h)) + + +# Driver code (NO INDENTATION) +arr = [10, 7, 8, 9, 1, 5] +quickSortIterative(arr, 0, len(arr) - 1) +print(arr) +# TC - O(nlogn) +# SC - O(logn) - average O(n^2) worst case \ No newline at end of file