Divide and Conquer Pattern¶
This pattern involves dividing a data set into smaller chunks and then repeating a process with a subset of data.
This pattern can tremendously decrease time complexity.
search(arr, val)
¶
Given a sorted array of integers, write a function called
search
, that accepts a value and returns the index where the value passed to the function is located. If the value is not found, return -1.
1 2 3 |
|
-
Solution 1 (naive)
-
Time: $O(n)$
1 2 3 4 5 6 |
|
-
Solution 2 (binary search)
-
Time: $O(\log n)$
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|