Last active
December 18, 2016 09:07
-
-
Save vsvankhede/e12cf4a44cbf30773f5934b0e70fc289 to your computer and use it in GitHub Desktop.
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
/** | |
* Find element position in sorted int array using binary search. | |
* Time- O(long n) Space- C | |
*/ | |
static int binSearch(int[] A, int k) { | |
int l = 0; | |
int u = A.length - 1; | |
int m; | |
while (l <= u) { | |
m = l + (u - l) / 2; | |
if(A[m] < k) { | |
l = m + 1; | |
} else if(A[m] == k) { | |
return m; | |
} else { | |
u = m - 1; | |
} | |
} | |
return -1; | |
} |
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
/** | |
* Functio to search the square root of given unsinged int. | |
* Input: unsined 32-bit int. | |
*/ | |
static int squareRootSearch(int k) { | |
int l = 0; | |
int u = 65536; | |
int m; | |
while (l + 1 < u) { | |
m = l + (u - l) / 2; | |
int mSquare = m * m; | |
if(k > mSquare) { | |
l = m; | |
} else if (k == mSquare) { | |
return m; | |
} else { | |
u = m; | |
} | |
} | |
return l; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment