Practicing inserting data into an array by using binary search, few problems
Posted
by
HelpNeeder
on Stack Overflow
See other posts from Stack Overflow
or by HelpNeeder
Published on 2012-09-30T03:11:50Z
Indexed on
2012/09/30
3:37 UTC
Read the original article
Hit count: 201
I'm trying to create a method which inserts and then sort elements in form of binary form.
The problem I am experiencing that my code doesn't insert data correctly which means that output does not appear to be in order at all.
The list is not organized, and data is added in order that is being inserted.
Now, 2 questions, what am I doing wrong here? And how to fix this?
public void insertBinarySearch(long value) // put element into array
{
int j = 0;
int lower = 0;
int upper = elems-1;
int cur = 0;
while (cur < elems)
{
curIn = (lower + upper ) / 2;
if(a[cur] < value)
{
j = cur + 1;
break;
}
else if(a[cur] > value)
{
j = cur;
break;
}
else
{
if(a[cur] < value)
lower = cur + 1;
else
upper = cur - 1;
}
}
for(int k = elems; k > j; k--)
a[k] = a[k-1];
a[j] = value;
elems++;
}
© Stack Overflow or respective owner