I am trying to get the math correct in my algorithm, but I am having a really hard time understanding the “Analysis of algorithms” calculating i.e f(n) = 1 or f(n) = n-1 etc..
I have created a method which loops through a sorted array of integers, and counting how many different integers there are (i.e {1,3,3,3,5,6,8} = 5). How do I calculate the worst case scenario?
Basically, the code is like this:
int length = a.length;
int diffCount = 1; //The number of different integers
for(int i = 1; i < length; i++)
{
int b = a[i];
int c = a[i-1];
if(c>b)
throw new IllegalStateException("unsorted array");
if(c!=b)
diffCount++;
}
return diffCount;
There’s some other stuff there aswell, but that’s just to prevent bugs like empty arrays and such, so I didn’t include it.
And what is the worst case scenario here..? If the condition c!=b is true every time?
In terms of run-time analysis, this algorithms is always O(n), if the array is sorted. If not, it will throw an exception before that (but worst case still is O(n)).
There are slightly different outcomes depending on the values. See Peter’s answer for an explanation of branch prediction. But I don’t think that this will influence the run time significantly.