Searching and Sorting
Searching and Sorting
Searching-
1. Linear search -
Most basic search goes through each element and searches for the required number.
2. Binary search
We can use binary search on a sorted array (monotonic function) – which means only increasing
or decreasing.
1.find the starting and ending index for the given sorted array
2.find the mid point of the array mid = (start+end)/2
3. check if the middle element matches the required number ? and now depending on if the
middle number is smaller than the required number or larger than the required number …if its
bigger we search the right side of the array and if its smaller then we search the left since the
array is sorted.
4.start end values need to be updated to the new half that we are looking for the number in.
3.Not in the right side of the array I follow the same process …so on the right side the middle
element will be 60.
With every iteration in binary search the array size is halved so it’s a lot better than linear search.
Since the array is sorted this should work. After the point where the number is missing there the
pattern will break and you will have to start doing +2