Answer to Question #243549 in Algorithms for kofi

Question #243549

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
Expert's answer
2021-09-28T15:32:08-0400

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)"

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS