简体   繁体   English

数组函数的时间复杂度

[英]the time complexity of array function

I wrote a function to find the position where the target value should be inserted in the given array. 我编写了一个函数来查找目标值应在给定数组中插入的位置。 We assume the array has distinct values and is sorted in ascending order. 我们假设该数组具有不同的值,并按升序排序。 My solution must be in O(log N) time complexity 我的解决方案必须是O(log N)时间复杂度

public static int FindPosition(int[] A, int target) {


    int a = A.length / 2;
    System.out.println(a);
    int count = a;
    for (int i = a; i < A.length && A[i] < target; i++) {
        count++;
    }
    for (int i = a; i > A.length && A[i] > target; i--) {
        count++;
    }
    return count;
}

Does this code have complexity of O(log N)? 此代码是否具有O(log N)的复杂度?

Short answer 简短答案

No. 没有。

Longer answer 更长的答案

With increments of 1 in your indices, you cannot expect to have a better solution than O(n) . 索引中的增量为1时,就不能期望有比O(n)更好的解决方案。

If your algorithm works at all (I don't think it does), it looks like it would need O(n) steps. 如果您的算法完全可行(我认为它不可行),则似乎需要O(n)步骤。

Also, you say you assume that the array is sorted, but you sort it anyway. 另外,您说您假设数组已排序,但是无论如何都对其进行了排序。 So your code is O(n*log(n)) . 所以你的代码是O(n*log(n))

What's more, trying to sort an already sorted array is the worst case for some sorting algorithms : it might even be O(n**2) . 而且,对于某些排序算法,尝试对已经排序的数组进行排序是最糟糕的情况:甚至可能是O(n**2)

You're looking for a binary search . 您正在寻找二进制搜索

No it isn't nlogn 不,这不是nlogn

public static int FindPosition(int[] A, int target){
/*
Time taken to sort these elements would depend on how
sort function is implemented in java.  Arrays.sort has average 
time complexity of Ω(n log n), and worst case of O(n^2)
*/
Arrays.sort(A);


/*Time taken to run this loop = O(length of A) or O(N) 
where N = arraylength
*/

for(int i=a;i<A.length&&A[i]<target;i++){
    count++;
}
/*Time taken to run this loop = O(length of A) or O(N) 
where N = arraylength
*/
for(int i=a;i>A.length&&A[i]>target;i--){
    count++;
}
return count;
}

Now time complexity would be represented by the longest of above three, since assignments and all are done in constant time. 现在,时间复杂度将由以上三个中的最长者来表示,因为分配和所有操作都在固定时间内完成。

Thus making your complexity O(n^2) in worst case. 因此,在最坏的情况下会使您的复杂度为O(n ^ 2)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM