Can anyone help me fix this problem I have with my code. I am supposed to be writing a Binary Insertion Sort method that calls a binary search method. I have code that is working for in order integers, when tested on reverse order integers it works except it places the middle term + 1 at the end (If size was 1000, 501 would be at the end), and it does not work at all for random order. Here is the code:
public static void sortBinary(Comparable [] x)
{
int insert,i,j;
Comparable temp;
for(i=1;i<x.length;i++)
{
insert = binarySearch(x,x[i]);
if(insert < i)
{
temp = x[i];
for(j=i-1;j>=insert;j--)
{
x[j+1]=x[j];
}
x[insert]=temp;
}
}
}
public static int binarySearch(Comparable [] x,Comparable temps)
{
int low = 0;
int high = x.length - 1;
int state;
while(low<=high)
{
int mid =(low + high)/2;
state = (x[mid]).compareTo(temps);
if(state == 0)
{
return mid;
}
else if(state < 0)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return 0;
}
If you could help I would greatly appreciate it.