Skip to content

Instantly share code, notes, and snippets.

@RitamChakraborty
Created August 11, 2019 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RitamChakraborty/d786b27bef4526fdc65a557c48e567c5 to your computer and use it in GitHub Desktop.
Save RitamChakraborty/d786b27bef4526fdc65a557c48e567c5 to your computer and use it in GitHub Desktop.
Binary Search in iterative way
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