我编写了此函数,用于将元素插入到排序的数组中,以便在添加元素后仍可以对数组进行排序。
但是出了点问题。我知道我的代码有很多极端情况,也许我已经使算法复杂化了,但是我真的想修复它。
我的代码:
private static <E> void insert(E e, E[] arr, int count, Comparator<E> comp) {
if (count == 0) arr[0] = e;
for (int i = 0; i < count; i++) {
if (comp.compare(arr[i], e) >= 0) {
// we found an element that is >= to e
// we want to add new element at index i, currently arr[i] is occupied
// by larger element, so we need to adjust
if (i != 0) {
i--;
} else {
// do nothing
}
} else if (i + 1 == count) {
// this is the last iteration of the loop so we want to add element at i + 1
i++;
} else {
// keep looping to find an element
continue;
}
// we need to move elements to the right to make space
for (int j = count; j > i; j--) {
arr[j] = arr[j - 1];
}
arr[i] = e;
break;
}
}
答案 0 :(得分:1)
我已修复代码,不应该减少i
private <E> void insert(E e, E[] arr, int count, Comparator<E> comp) {
if (count == 0) {
arr[0] = e;
return;
}
for (int i = 0; i < count; i++) {
if (comp.compare(arr[i], e) >= 0) {
// we found an element that is >= to e
// we want to add new element at index i, currently arr[i] is occupied
// by larger element, so we need to adjust
} else if (i + 1 == count) {
// this is the last iteration of the loop so we want to add element at i + 1
i++;
} else {
// keep looping to find an element
continue;
}
// we need to move elements to the right to make space
for (int j = count; j > i; j--) {
arr[j] = arr[j - 1];
}
arr[i] = e;
break;
}
}