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

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.

Related

How can i count how many times the keywords user enter is the used in the essay. its doesn't check on the entire keyword [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 6 years ago.
Improve this question
public static int keywordsChecker(String essay,String key) {
int count = 1;
String[] k=key.split(",");
for (int i = 0; i < k.length-1; i++) {
if (essay.contains(k[i])) {
count++;
}
}
return count;
}
To take into account that each keyword searched for may occur more than once, and to count such occurrences, you may use this inside your for loop:
int indexOfOccurrence = essay.indexOf(k[i]);
while (indexOfOccurrence > -1) {
count++;
indexOfOccurrence = essay.indexOf(k[i], indexOfOccurrence + 1);
}
There are a couple of other issues in your code: I believe you need to initialize count to 0 (not 1). And to count also the last keyword in key your for loop should be for (int i = 0; i < k.length; i++) (without subtracting 1 from k.length). If you want, using <= would also work: for (int i = 0; i <= k.length-1; i++), but this is non-standard, so I would not recommend it.

Code not Working For Large Permutations [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 8 years ago.
Improve this question
I've just completed a codility test and only achieved a score of 81%. My code failed when a 'large permutation' was tested against it.
I've got no idea why this failed, as the spec says all values are integers, and my for loop uses only int values. I would really appreciate it if somebody could look at my code and tell me why it provides a value of -1 for massive permutations:-
https://codility.com/demo/results/demo4G8CJS-9YN/
class Solution {
public int solution(int X, int[] A) {
// write your code in Java SE 8
int target = X;
int[] path = new int[X];
for(int i = 0; i < A.length-1; i++) {
if(A[i] != path[A[i]-1]) {
path[(A[i]-1)] = A[i];
target--;
}
if(target==0) {
return i;
}
}
return -1;
}
}
It should be for (int i = 0; i < A.length; i++)(not i < A.length - 1). As of now, the last element of the array is just ignored. It actually fails a very simple test: an array of one element and X = 1.

Netbeans telling me that a value is boolean when it is an int [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 8 years ago.
Improve this question
my while loop :
while (j =>0&& (courseArray[j].compareByCourse(value)) >=0 ){
}
is giving me this error in netbeans: int cannot be converted to boolean
method:
public static void insertionSort(Course[] courseArray){
Course value ; // the next value from the unsorted list to be inserted into the sorted list
int i; // i is a pointer to an item in the unsorted list
int j; // j is a pointer to an item in the sorted list; originally the sorted list is just a[0]
int compare;
for (i=1; i<courseArray.length; i++){
value = courseArray[i];
j = i -1;
compare = courseArray[j].compareByCourse(value);
while (j =>0&& (courseArray[j].compareByCourse(value)) >=0 ){
}
}
}
compareByCourse method:
//method to compare Courses by course name
int compareByCourse(Course other){
return this.course.compareTo(other.getCourse());
}
j is an int, the return value is an int, 0 is an int, so where is the boolean?
It seems like you have confused the operator >= with => (which is not a valid operator in Java). Try changing the while condition to:
while (j >= 0 && (courseArray[j].compareByCourse(value)) >= 0 )
Also if you are assigning j to:
compare = courseArray[j].compareByCourse(value);
use it in the while loop (you can also use it directly).

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}.

What's wrong with this binary search? [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 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.

Categories

Resources