What's wrong with this binary search? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
public static int binsrch (int[] a, int key) {
int low = 0;
int high = a.length - 1;
while (true) {
if (low > high) return -(low+1);
int mid = (low + high)/2;
if (a[mid] < key) low = mid + 1;
else if (a[mid] > key) high = mid - 1;
else return mid;
}
Can anybody help?

There are at least two, possibly three, things I can see wrong with it.
It uses (low + high)/2. The addition may overflow to a negative number if the array is very large. If so, division by 2 will lead to a negative index. This can be fixed by using (low + high)>>>1.
It is not documented. I am guessing that it is intended to return the match index if it finds the key in the array, and a negative value on miss. I am not sure exactly what the negative result is supposed to represent, due to the lack of documentation.
Depending on the missing specification, there may be additional problems.

Related

how to exclude zero from the range [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am learning Java, at a very beginning level. I am trying to print the Dice result, so from 1 to 6.
//instance of random class
Random DICE = new Random();
int DiceRange = 7;
int RIGHT = DICE.nextInt(DiceRange);
int LEFT = DICE.nextInt(DiceRange);
System.out.println("Right Dice = " + RIGHT);
System.out.println("Left Dice = " + LEFT);
The issue with this code that "Zero" is also printed sometimes. I want to keep the range from 1 to 6, instead of 0 to 6.
I tried to do the following, but did not work:
int i = 0;
while (DiceRange == 0); {
i++;
}
The CPU went to 100% :)
So how to exclude zero from this?
From Random documentation:
public int nextInt(int bound)
Returns a pseudorandom, uniformly distributed int value between 0
(inclusive) and the specified value (exclusive)
So starting from your code you can solve your problem using :
Random DICE = new Random();
int DiceRange = 6;
int RIGHT = DICE.nextInt(DiceRange) + 1;
int LEFT = DICE.nextInt(DiceRange) + 1;

Understanding a modified variant of Sieve of Eratosthenes algorithm [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I came across this algorithm on a coding site (There was no author's information) which counts all prime numbers less than a given limit. It looks very similar to SoE algorithm but it is different in the way it counts the primes:
public int countPrimes(int n) {
if (n < 3) return 0;
boolean[] s = new boolean[n];
int c = n / 2;
for (int i = 3; i < Math.sqrt(n); i += 2) {
if (s[i]) continue;
for (int j = i * i; j < n; j += 2 * i) {
if (!s[j]) {
c--;
s[j] = true;
}
}
}
return c;
}
It sets the initial count to half the limit then decrement it, but I can not seem to understand why does this work. Can anyone please explain?
First of all, the boolean array s represents SoE.
The first loop iterates odd numbers from 3 to sqrt(n) (Because all even except 2 is not prime).
At the 6th line, If i is already in the s, continue to next odd number. If not, add all multiple of i that is less or equal to n to s in the second loop.
In addition, the second loop starts from i*i because all multiple of i smaller than i*i are already checked in prior loops.
The count is initialized to n/2 because all even numbers (except 2) are not primes.
And then the loop below can start checking from multiples of 3.
If a new non-prime is found (!s[j]), the count of primes (c) is decreased.

Using Binary Search to Find Insertion Points in an Array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I need to modify the below code to use binary search to return the Index of an Insertion Point in a sorted Array
for Instance if objArray={1,2,4} and searchObj=3
the binarysearch function should return 2 as the Index where 3 should be inserted
public int binarySearch(Comparable[] objArray, Comparable searchObj)
{
int low = 0;
int high = objArray.length - 1;
int mid = 0;
while (low <= high)
{
mid = (low + high) / 2;
if (objArray[mid].compareTo(searchObj) < 0)
{
low = mid + 1;
}
else if (objArray[mid].compareTo(searchObj) > 0)
{
high = mid - 1;
}
else
{
return mid;
}
}
return -1;
}
Thanks
Your code is a Binary Search, which returns the index of the element or -1 if it didn't exists at all.
If you just need to return the index where it should be inserted, then you should change your line return -1; to return mid;.
But keep in mind that this approach will return either the index of that element OR the index where it should be inserted. So you will need another test to identify if the item already exists in your array.
Maybe, a better approach would be to use a Binary Tree.

Why does the modulus not help to find negative odd number? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
What I am doing: Replacing odd numbers(values) in array with zeros.
Problem: when executing following code it replaces only positive numbers, ignoring negative.
Code:
public static int[] nullOddValues(int[] array) {
int[] resultArray = new int[array.length];
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 != 0) {
resultArray[i] = 0;
} else {
resultArray[i] = array[i];
}
}
return resultArray;
}
You test the loop variable i for oddity when you (probably) want to test array[i]
if (array[i] % 2 != 0) {
Using modulus on X returns [0-X)
positive X (X > 0) -> it will return 0+
negative X (X < 0) -> it will return 0-
For your problem, I recommend using a bit operator
if((i & 1) == 0)
This will return true for even numbers (positive and negative), since it is checking the last bit of the number.

How can I locate an index given the following constraints? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Given an array of n integers A[0…n−1], such that ∀i,0≤i≤n, we have that |A[i]−A[i+1]|≤1, and if A[0]=x, A[n−1]=y, we have that x<y. Locate the index j such that A[j]=z, for a given value of z, x≤ z ≤y
I dont understand the problem. I've been stuck on it for 4 days. Any idea of how to approach it with binary search, exponential search or interpolation search recursively? We are given an element z find the index j such that a [j] = z (a j) am i right?.
This:
| A[i]−A[i+1] | ≤ 1
means that each element in your array will be at most one different(-ve or +ve). It then follows that the closest index that can contain z from the current is |A[cur] - z| spaces away.
So, what you do is start with j=0, and figure it out for each step. Jump that many spaces, and check again. Eventually you'll find z or reach the end.
public static int findZ(int[] a, int z){
int j = 0;
while(j < a.length){
if(a[j] == z)
return j
j += Math.abs(a[j] - z);
}
return -1;
}
This isn't a binary or exponential search, and it's not recursive, but it's simple and gets the job done. It works as a one-sided interpolation search. See below for the two-way method. You can turn it into a recursive function, but that should be straightforward and I'll leave that to you.
It runs in O(n), where your worst case performance is going to be on something like {0,0,0,0,1}, where it can only jump one step, and turns into a straight linear search.
Best case will be ordered, distinct members like {0,1,2,3,4,5}, where it will only perform one jump.
Edit:
In the interests of making this more "interpolation search-like", let's move both the upper and lower bounds at the same time. The same logic applies for both ends:
public static int findZ(int[] a, int z){
int j = 0;
int k = a.length - 1;
while(j <= k){
if(a[j] == z)
return j
if(a[k] == z)
return k;
j += Math.abs(a[j] - z);
k -= Math.abs(a[k] - z);
}
return -1;
}
It still ends up as O(n) overall worse case, but this is normal for an interpolation search.
Now your worst case is more like {0,0,0,1,0,0,0}, and your best is like {0,1,2,3,2,1,0}.

Categories

Resources