我的insertInOrder方法是錯誤的(它向後打印數字列表)。我正在閱讀數字列表,並且我想使用插入排序算法來使用二進制搜索的索引位置以升序排列數字。我不確定如何去解決這個問題,並且非常感謝。二進制搜索和插入排序
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
這是insertInOrder在我的主要
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
你只能做一個已排序數組的二進制搜索。 – halex
請顯示一些如何調用'insertInOrder(i [],i,i)'的例子。 – aliteralmind
我正在逐一讀取數字,但我想使用二進制搜索來查找下一個傳入數字的插入索引 – user3287300