我需要创建一个方法,将整数插入到已排序的整数数组中。 我已经完成了这个方法,但不是使用整数而是使用字符串。现在我遇到了整数问题。
我使用字符串数组的方法是:
public int inserisci(String s) throws IllegalStateException {
if(numElementi == elementi.length)
throw new IllegalStateException("Full array.");
int pos = ricercaBinaria(s);
if(pos > -1)
return -1;
if(elementi[-(pos + 1)] != null) {
for(int i = numElementi; i >= -(pos + 1); i--)
elementi[i + 1] = elementi[i];
}
elementi[-(pos + 1)] = s;
numElementi++;
return -(pos + 1);
}
对于字符串数组,我写了这个:
public int insert(int x) throws IllegalStateException {
if(numElements == elements.length)
throw new IllegalStateException("Full array.");
int pos = binarySearch(x);
if(pos > -1)
return -1;
if(**elements[-(pos + 1)] != null**) {
for(int i = numElements; i >= -(pos + 1); i--)
elements[i + 1] = elements[i];
}
elements[-(pos + 1)] = x;
numElements++;
return -(pos + 1);
}
但是粗体部分(elements[-(pos + 1)] != null)不正确。我该如何更换它? 谢谢
最佳答案
- 如果你在列表和集合排序中使用java的构建,它一定比你当前的方法更快
- 像 -(pos + 1) 这样的语法对于可读性和重新排列数组的向后方式非常不利,如果您要使用此方法,请找到要插入的位置,例如索引“i”当前正在使用 - 它们在插入 i 之前将 i 之后且等于 i 的所有其他元素向上移动一个。 (我认为这一定是个人发展或学校作业,因为您不想在公司 java 代码上执行此逻辑)
关于java - 如何将整数元素插入排序数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23037304/