【发布时间】:2015-02-18 11:13:56
【问题描述】:
我想分析下面程序的执行时间复杂度。 请用解释回答。
private static void printSecondLargest(int[] arr) {
int length = arr.length, temp;
for (int i = 0; i < 2; i++) {
for (int j = i+1; j < length; j++) {
if(arr[i]<arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println("Second largest is: "+arr[1]);
}
【问题讨论】:
-
内部循环运行
(2* arr.length)-2次完全。复杂度为O(n) -
O(n) 是程序的复杂度。
-
@TheLostMind 感谢您的回答。但是你的答案是正确的,但解释有点不正确。它会执行 (2* arr.length) - 3 次。
-
@RahulChaubey - 没错。 1 +2 --> 3.. :)
标签: java algorithm data-structures big-o asymptotic-complexity