我正在尝试测试我对 BigO 的了解不是很自信也不是完全文盲,但请指导。
这不是家庭作业,我不是任何地方的学生,但有兴趣理解这个和其他各种相关概念。
//What is bigO of this Application ?
public class SimpleBigOTest {
// What is BigO of this method -> I am certain it is O(n) but just checking
private void useItirativeApprachToPrintNto0(int n) {
for (int i = 0; i < n; i++) {
System.out.println("useItirativeApprachToPrintNto0: " + i);
}
}
// What is BigO of this method -> I am reasonabily certain it is O(n)
private void useRecurrsiveApprachToPrintNto0(int n) {
if (n != 0) {
System.out.println("useRecurrsiveApprachToPrintNto0: " + n);
useRecurrsiveApprachToPrintNto0(n - 1);
}
}
// What is BigO of this method -> I think now it is O(n^2)
private void mutltipleLinearItirationsDependentOnValueOfN(int n) {
int localCounter = n + n;
for (int i = 0; i < localCounter; i++) {
System.out.println("mutltipleLinearItirationsDependentOnValueOfN: "
+ i);
}
for (int i = 0; i < n; i++) {
System.out.println("mutltipleLinearItirationsDependentOnValueOfN: "
+ i);
}
}
// What is BigO of this method -> I think this is again O(n)
private void mutltipleLinearItirationsNotDependentOnValueOfN(int n, int j) {
int localCounter = j;
for (int i = 0; i < localCounter; i++) {
System.out
.println("mutltipleLinearItirationsNotDependentOnValueOfN: "
+ i);
}
for (int i = 0; i < n; i++) {
System.out
.println("mutltipleLinearItirationsNotDependentOnValueOfN: "
+ i);
}
}
// What is bigO of this main -> I would say O(n^2) because
// mutltipleLinearItirationsDependentOnValueOfN has biggest BigO of O(n^2)
// if I am correct
public static void main(String[] args) {
SimpleBigOTest test = new SimpleBigOTest();
int n = 1000;
int j = 1234;
test.useItirativeApprachToPrintNto0(n);
test.useRecurrsiveApprachToPrintNto0(n);
test.mutltipleLinearItirationsDependentOnValueOfN(n);
test.mutltipleLinearItirationsNotDependentOnValueOfN(n, j);
}
}
作为一个附带问题,为什么所有关于算法的书籍都如此高度评价递归,而在我的实践经验中,我一直使用迭代。使用递归,我们可以快速耗尽内存并进行噩梦般的调试。