简体   繁体   中英

the Time complexity of an algorithm

I am learning algorithms at the moment and wrote this below code, which finds if a peak exists in a one dimensional array. my question is how do I know its time complexity of its best case or average case?

The worst case time complexity (if the element of the array are sorted) is O(n), but if the array is not sorted and it has 10 elements the code runs 5 loops to get the result, which is half of the array size, so can anyone tell me how to write this in algorithmic notation.

 int[] arr = { 1,5,2,7,8,9,4,6,7};
 int peak;

 int count = 0;
 for (int i = 1; i < arr.Length - 1; i++)
 {
            peak = -1;
            if (arr[i - 1] <= arr[i] && arr[i] >= arr[i + 1])
            {
                peak = arr[i];
                i++;
            }
            else if (arr[i - 1] >= arr[i] && i - 1 == 0)
            {
                peak = arr[i - 1];
            }
            else if (arr[i + 1] >= arr[i] && i + 1 == arr.Length - 1)
            {
                peak = arr[i + 1];
            }

            if (peak != -1)
                listBox1.Items.Add(peak.ToString());

            count++;
}

listBox1.Items.Add(count.ToString());

You would still write it as O(n) because Big-O is worst case (which here is linear time.) In this case n is of course the array length. Theoretically nothing inside your loop exceeds O(1) (I'm going to ignore the list append and call it constant.)

After noticing your comments about n/2 iterations. n/2 is the same as saying (1/2)n or O((1/2)n) this is equivalent to O(n) because we ignore all coefficients when doing bounding with Big-O.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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