My insertInOrder method is wrong(it prints the list of numbers backwards). I am reading in a list of numbers, and I want to use the insertion sort algorithm to sort the numbers in ascending order using the index position of the binary search. I am not really sure how to go about this and help would be very much appreciated.
static void insertInOrder( int[] arr, int cnt, int newVal ) {
int index = bSearch( arr, 0, arr.length-1, newVal) ;
if (index < 0) {
index = -1 - index ;
}
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+hi)/2;
if(lo>hi)
return -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);
}
Reading in: 5 13 7 9 21
Current Output: 21 9 7 13 5
Desired Output: 5 7 9 13 21
This is insertInOrder in my main
int[] arr = new int[INITIAL_CAP];
int arrCnt= 0;
while (infile.hasNextInt())
{
if ( arrCnt==arr.length )
arr = doubleMyLength(arr);
insertInOrder( arr, arrCnt, infile.nextInt() );
++arrCnt;
}
infile.close();
arr = trimMyLength( arr, arrCnt );
System.out.println("Sorted array of " + arr.length + " ints from " + args[0] + " after insert in order:" );
printArray( arr ); // we trimmed it so count == length so we don't bother to pass in count