Created
August 11, 2019 18:22
-
-
Save RitamChakraborty/d786b27bef4526fdc65a557c48e567c5 to your computer and use it in GitHub Desktop.
Binary Search in iterative way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BinarySearchIterative { | |
public static int search(int[] arr, int num) { | |
int start = 0; | |
int end = arr.length - 1; | |
while (true) { | |
if (end - start == 1) { | |
if (arr[start] == num) { | |
return start; | |
} else if (arr[end] == num) { | |
return end; | |
} else { | |
return -1; | |
} | |
} else { | |
int mid = (start + end) / 2; | |
if (arr[mid] == num) { | |
return mid; | |
} else { | |
if (arr[mid] < num) { | |
start = mid; | |
} else { | |
end = mid - 1; | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment