Sairam Yendluri
BAN USERsairamyandluri7@gmail.com
O(log n) solution using Binary search notion :
#include <stdio.h>
#include <limits.h>
main() {
int minEle, f, a[] = { 10, 14, 32, 49, 51, 62, 77 }, n = 7,i,j,mid,min = INT_MAX,ele;
i = f = 0;
j = n - 1;
printf("Enter element : ");
scanf("%d",&ele);
printf("Nearest element is : ");
while( i <= j ) {
mid = (i+j)/2;
if(a[mid] == ele)
{
f = 1;
printf("%d\n",ele);
break;
}
if( min > abs(a[mid]-ele) ) {
min = abs(a[mid]-ele);
minEle = a[mid];
}
if( a[mid] > ele)
j = mid-1;
else
i = mid+1;
}
if( f == 0 )
printf("%d\n",minEle);
}
your answer is correct, but double checking lock won't solve problem completely. There was a problem due to java memory model, that is it allows out of order writes. Using volatile everything will be solved, since its atomic varible.
- Sairam Yendluri July 03, 2013:) yes ofcourse
- Sairam Yendluri July 02, 2013its utterly wrong. just disregard my solution
- Sairam Yendluri July 02, 2013yes, your code seems correct
- Sairam Yendluri July 02, 20132's complement of a negative number is simply a positive magnitude of that number. For example, if number is -6 its 2's complement will be 6.
I think this is the code
#include <stdio.h>
main() {
int a=-6;
a = (~a)+1;
printf("%d\n",a);
}
yes it won't work if key is duplicated more than once in a given array
- Sairam Yendluri July 02, 2013yes disregard my solution
- Sairam Yendluri July 02, 2013this is just traversal i'm not storing in array.
- Sairam Yendluri July 01, 2013Its actually an inplace recursive alogorithm.
code is passing till leftmost leaf node, then root and then right, continues. Its clearly inplace since no external memory is using for storing array elements. First trace the program clearly, if still doubt let me know.
Thanks
- Sairam Yendluri July 11, 2013