Binary Search is used to search for a key in a sorted array. It is a Divide and conquer algorithm.
- Find mid point of given list.
- Check if number at mid is equal to key. If equal then return mid.
- If not equal then it will search for key in one half of the list based on these condition -
- If number at mid of list is greater than key then search in first half of the list.
- If number at mid of list is smaller than key then search in second half of the list.
Best case - O(1)
Worst and Average case - O(log n) here n is size of list of numbers.
Partition algorithm separates a list of numbers based on a pivot such that numbers less than and equal to pivot are on the left side of the pivot and numbers greater than the pivot are on right side of the pivot. After partiton, pivot is the element which is present on its actual location in sorted array.
- Select pivot element.
- Take two variables i = 0 and j = -1.
- Variable j tells that all the element at index less than or equal to j are less than or equal to pivot and all the element to the right of index j till index i are greater than pivot eement.
- Scan the list once using "i" and whenever an element less than or equal to pivot occurs swap it element at index j+1(element which is greater than pivot).
- After scanning swap first element of list with element at index j, so that pivot is present at index j.
- Return j which is index of pivot.
Every Case - O(n) here n is size of list of numbers.
K-th smallest number can be found using partition algorithm. If the pivot index "m" returned by partition is equal to k then element at mth index is k-th smallest number. If pivot index returned by partiton is greater then k then apply partition on left part and if pivot index is less than k then apply partition on right part
Finding K-th largest number is same as finding "n - k + 1" th smallest element, here n is the length of array.
Merge sort is a divide and conquer algorithm