I am reading in a list with unsorted numbers:
5 24 27 23 8 6 19
I got the binary search down, but I don't know how to use it to insert values in order. I need to change my insertInOrder method, so that the numbers are in ascending order. My method right now doesn't really do anything except print the list backwards.
static void insertInOrder( int[] arr, int cnt, int newVal )
{
int index = -( bSearch( arr, 0, arr.length-1, newVal)) - 1;
{
for ( int i = cnt; i >= index+1 ; --i)
{
arr[i] = arr[i-1];
}
arr[index] = newVal;
}
}
public static int bSearch(int[] a, int lo, int hi, int key)
{
int mid = lo+(lo + hi)/2;
if (lo <= hi)
return -(lo+1);
else if (a[mid] == key)
return mid;
else if (a[mid] < key)
return bSearch(a, mid+1, hi, key);
else
return bSearch(a, lo, mid-1, key);
}
Edit:
input: 5 24 27 23 8 6 19
current output: 19 6 8 23 27 24 5
expected output: 5 6 8 19 23 24 27
input,current output, andexpected output, each clearly labeled as such. I think your input is5 24 27 23 8 6 19...? Not sure though...