CC-2 : Implement Binary Search Algorithm.
Description:
The binary search algorithm works on sorted lists. The algorithm checks and divides the input list into 2 lists (binary/two list) recursively and searches for the element within the partitioned sub list till the required element is found, or the conclusion is reached that the element does not exist in the sorted list. Since the original input list is sorted, if the element to be searched is lesser than the element at which the list is being partitioned, we need to search in the lower partition only and vice versa. Given a sorted input array and an element to be searched, search the required element in the input array using binary search.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| Array: 3, 22, 44, 67, 77, 96, 122, 144, 201, |
122 found at index 6 76 found at index -1 |
Pseudocode:
| Integer array named nums and integer named toSearch to be searched are received as input parameters. |
| Set integer variable firstIdx to zero, we will use this variable to check the first index of partition in which are searching for required integer. |
| Set integer variable lastIdx to nums.length-1, we will use this variable to check the last index of partition in which are searching for required integer. |
| While (firstIdx <= lastIdx) do the following steps:
Set integer variable midCount to (lastIdx-firstIdx)/2.
Set integer variable midIdx to (firstIdx+midCount)to get mid index of current partition. We will use midIdx to partition the array into 2 parts.
If (nums[midIdx]==toSearch) return midIdx; this means have found the required element.
Else if nums[midIdx > toSearch then:
Set lastIdx=(midIdx-1) as we need to search in lower partition now.
Else:
Set firstIdx=midIdx+1, as we need to search in the higher partition now.
|
| If toSearch is not found in code above return -1, as the required element does not exist within the input array. |
Code:
public int binarySearch(int[] nums, int toSearch){
int firstIdx=0;
int lastIdx=nums.length-1;
while (firstIdx <= lastIdx) {
int midCount=(lastIdx-firstIdx)/2;
int midIdx=firstIdx+midCount;
if (nums[midIdx]==toSearch) {
return midIdx;
} else { if (nums[midIdx]> toSearch) {
lastIdx=midIdx-1;
}else {
firstIdx=midIdx+1;
}
}
}
return -1;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |