我正在对我通过添加N个项目之前的系统时间和添加N个项目之后的时间所创建的ArrayList算法进行时间测试。通过分析代码,我知道算法的时间复杂度为O(1)。但是,运行这些测试时,我得到的时间不代表O(1)。我得到的时间如下。
n = 10,000 3.38毫秒
n = 100,000 13.43毫秒
n = 500,000 53.02毫秒
n = 1,000,000 121.2毫秒
我认为这是因为我要添加N个项目,并且为了使循环遍历这些项目,随着N变大,它会增加额外的时间。
是否可以排除重复遍历N个项目所需的时间?
这是我的算法,显示它肯定是O(1)。
public boolean addLast(E obj) {
if (this.isFull()) {
return false;
}
if (obj == null) {
System.out.println("Invalid data, ignoring");
return false;
}
int idx;
if (this.isEmpty()) {
idx = this.arrRear;
} else {
if (this.arrRear + 1 < this.circArr.length) {
idx = this.arrRear + 1;
} else {
idx = 0;
}
}
this.circArr[idx] = obj;
this.arrRear = idx;
this.items++;
this.modsMade++;
return true;
}