c# - the Time complexity of an algorithm -
i learning algorithms @ moment , wrote below code, finds if peak exists in 1 dimensional array. question how know time complexity of best case or average case?
the worst case time complexity (if element of array sorted) o(n), if array not sorted , has 10 elements code runs 5 loops result, half of array size, can tell me how write in algorithmic notation.
int[] arr = { 1,5,2,7,8,9,4,6,7}; int peak; int count = 0; (int = 1; < 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] && - 1 == 0) { peak = arr[i - 1]; } else if (arr[i + 1] >= arr[i] && + 1 == arr.length - 1) { peak = arr[i + 1]; } if (peak != -1) listbox1.items.add(peak.tostring()); count++; } listbox1.items.add(count.tostring());
you still write o(n)
because big-o worst case (which here linear time.) in case n
of course array length. theoretically nothing inside loop exceeds o(1)
(i'm going ignore list append , call constant.)
after noticing comments n/2
iterations. n/2
same saying (1/2)n
or o((1/2)n)
equivalent o(n)
because ignore coefficients when doing bounding big-o.
Comments
Post a Comment