有人能告诉我这个算法的时间复杂度是多少吗?
请记住:第二个方法 (findMax) - 根据其获取的索引在数组上运行,这意味着该方法 (findMax) 不会每次都在所有数组上运行。
我认为这个算法的时间复杂度是 O(n) 但也许我错了。
public class Q2 {
public static int[] replace(int []a)
{
for(int i = 0; i < a.length; i++ ){
if(i == a.length-1){
a[i] = 0;
}
int maxSubArry = findMax(a,i);
swap (a, i, maxSubArry);
}
return a;
}
public static int findMax (int[]a, int i)
{
// i = i +1;
int tmp = 0;
for(i = i +1; i<a.length; i++)
{
if(a[i] > tmp)
tmp = a[i];
}
return tmp;
}
public static void swap(int[]a, int i, int maxSubArry)
{
int temp = a[i];
a[i] = maxSubArry;
a[i+1] = temp;
}
}
your replace
方法更像是冒泡排序算法,算法复杂度为O(n*n)
.
AND的初始值findMax
应该Integer.MIN_VALUE
。并且 if 语句是不必要的replace
.
public static int[] replace(int[] a) {
for (int i = 0; i < a.length-1; i++) {
swap(a, i, findMax(a, i));
}
return a;
}
public static int findMax(int[] a, int i) {
int tmp = Integer.MIN_VALUE;
for (i = i + 1; i < a.length; i++) {
if (a[i] > tmp)
tmp = a[i];
}
return tmp;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)