Skip to content

Instantly share code, notes, and snippets.

@jpt1122
Created October 23, 2015 07:16
Show Gist options
  • Save jpt1122/0ec3e9f8a69ed932c4f6 to your computer and use it in GitHub Desktop.
Save jpt1122/0ec3e9f8a69ed932c4f6 to your computer and use it in GitHub Desktop.
Find SQRT with help of Binary Search
public class FindSqrt {
public static int sqrt(int no) {
int result = 0;
int low = 0, high = (no / 2), mid = 0;
int midVal = 0;
while (low <= high) {
mid = (low + high) / 2;
System.out.println("Mid Point :" + mid);
midVal = mid * mid;
if (midVal == no) {
result = mid;
break;
} else if (midVal > no) {
high = mid - 1;
} else if (mid < no) {
low = mid + 1;
}
}
return result;
}
public static void main(String[] args) {
System.out.println("Final ::" + sqrt(64));
}
}
/*
Output :
Mid Point :16
Mid Point :7
Mid Point :11
Mid Point :9
Mid Point :8
Final ::8
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment