Q1. Write the code necessary to find the largest element in an unsorted array of integers. What is the time complexity of this algorithm?
Q2. Determine the growth function and order of the following code fragment:
for (int count=0; count < n; count++)
{
for (int count2=0; count2 < n; count2=count2+2)
{
System.out.println(count, count2);
}
}
1.
int max;
if (intArray.length>0)
{
max=intArray[0];
for (int num=1;num<intArray.length;num++)
if (intArray[num]>max)
max=intArray[num];
System.out.println(max);
}
else
{
System.out.println("The array is empty.");
}
The time complexity of the given algorithm of finding the largest element in an unsorted array is O(n), where n is the array size.
2.
The outer loop runs n times.
The inner loop runs 1 time if n=1,2; 2 times if n=3,4; 3 times if n=5,6; 4 times if n=7,8; etc.
So, the growth function:
"f(n)=n\\cdot n\/2=n^2\/2"
order: "O(n^2)"
Comments
Leave a comment