[英]Java - Binary insertion sort, troubleshoot
I have a task where I need sort an array using binary insertion sort. 我有一项任务,需要使用二进制插入排序对数组进行排序。 This is the solution I came up with, but it is too slow:
这是我想出的解决方案,但是它太慢了:
public static void binaryInsertionSort(int[] a) {
int ins, i, j;
int tmp;
for (i = 1; i < a.length; i++) {
ins = BinarySearch (a, 0, i, a[i]);
if(ins < i) {
tmp = a[i];
for (j = i - 1; j >= ins; j--)
a[j+1] = a[j];
a[ins] = tmp;
}
}
}
private static int BinarySearch(int[] a, int low, int high, int key) {
int mid;
if (low == high)
return low;
mid = low + ((high - low) / 2);
if (key > a[mid])
return BinarySearch (a, mid + 1, high, key);
else if (key < a[mid])
return BinarySearch (a, low, mid, key);
return mid;
}
I was recommended to use System.arraycopy method which I have tried, but I do not understand why it is not working: 建议我使用我尝试过的System.arraycopy方法,但是我不明白为什么它不起作用:
public static void binaryInsertionSort(int[] a) {
int ins, i;
int tmp = a[i];
for (i = 1; i < a.length; i++) {
ins = binarySearch (a, 0, i, a[i]);
if(ins < i){
System.arraycopy(a, ins, a, ins + 1, i - ins);
a[ins] = tmp;
}
}
}
private static int binarySearch(int[] a, int low, int high, int key) {
int mid;
if (low == high)
return low;
mid = low + ((high - low) / 2);
if (key > a[mid])
return binarySearch (a, mid + 1, high, key);
else if (key < a[mid])
return binarySearch (a, low, mid, key);
return mid;
}
Any assistance is helpful. 任何帮助都是有帮助的。
Well, in the meantime the answer was easier than I thought. 好吧,与此同时,答案比我想的要容易。 I initialized the local variable in the wrong place.
我在错误的地方初始化了局部变量。 Instead of:
代替:
public static void binaryInsertionSort(int[] a) {
int ins, i, j;
**int tmp = a[i];**
for (i = 1; i < a.length; i++) {
ins = BinarySearch (a, 0, i, a[i]);
if(ins < i){
tmp = a[i];
for (j = i - 1; j >= ins; j--)
a[j+1] = a[j];
a[ins] = tmp;
}
}
}
The correct way is to: 正确的方法是:
public static void binaryInsertionSort(int[] a) {
int ins, i;
for (i = 1; i < a.length; i++) {
**int tmp = a[i];**
ins = binarySearch (a, 0, i, a[i]);
if(ins < i){
System.arraycopy(a, ins, a, ins + 1, i - ins);
a[ins] = tmp;
}
}
}
And it works (: 它可以工作(:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.