我的算法的复杂性
Complexity of my Algorithm
问题:哪个复杂性有我的功能?以及如何找到我的算法的时间复杂度?
该函数检查给定的 int 数组是否已排序。
我的代码:
public static boolean isSorted(double d[]){
boolean sortedAscending = true;
boolean sortedDescending = true;
boolean bool = false;
for (int i = 0; i < d.length-1; i++) {
if(d[i] > d[i+1] && sortedAscending){
sortedAscending = false;
if(bool){
break;
}
bool = true;
}
else if(d[i] < d[i+1]&& sortedDescending){
sortedDescending = false;
if(bool){
break;
}
bool = true;
}
}
return sortedAscending || sortedDescending;
}
这只是一个单循环程序,每次迭代都执行恒定的时间。时间复杂度是线性的 - O(n)
其中 n
是数组长度。
问题:哪个复杂性有我的功能?以及如何找到我的算法的时间复杂度?
该函数检查给定的 int 数组是否已排序。
我的代码:
public static boolean isSorted(double d[]){
boolean sortedAscending = true;
boolean sortedDescending = true;
boolean bool = false;
for (int i = 0; i < d.length-1; i++) {
if(d[i] > d[i+1] && sortedAscending){
sortedAscending = false;
if(bool){
break;
}
bool = true;
}
else if(d[i] < d[i+1]&& sortedDescending){
sortedDescending = false;
if(bool){
break;
}
bool = true;
}
}
return sortedAscending || sortedDescending;
}
这只是一个单循环程序,每次迭代都执行恒定的时间。时间复杂度是线性的 - O(n)
其中 n
是数组长度。