Question

Derive the worst case big O time to find the 5th largest item in an unsorted...

Derive the worst case big O time to find the 5th largest item in an unsorted array of length n. Assume n is much larger than 5. You can modify the way the array items are arranged. No code needed just explain what the big o is, which data structure/algorithm you used if any, and explain.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

let we use array a[ ] to store our numbers. And size of array is n. Now we have to find 5th largest element for that we can use following algorithm.

1. Find_5th_largest(array a[ ])

2.{ int largest[5] ={0,0,0,0,0};

4.int i

5. for(i=0;i<n;i++)

6. {

7. if (a[i]>largest[0]) { largest[0] = a[i] }

8. elseif(a[i]>largest[1] { largest[1] = a[i] }

9. elseif( a[i] >largest[2]) { largest[2]=a[i]}

10. elseif (a[i]>largest[3] ) {largest[3]=a[i] }

11. elseif( a[i]>largest[4] ) {largest[4] = a[i] }

12. }

13. So 5th largest number is largest[4].

Explanation of code- We declare an array largest that can hold 5 numbers. Now at first we set numbers of largest array to 0.

Now we execute loop of i from 0 to n. and at each iteration we check whether value of a[i] is greater than value present in largest[] array. Now 0 index of largest array contain largest element of array 1st index of largest array contain second largest element of array and similarly 4th index contain fifth largest element of array. So at each iteration we check a[i] to largest[0] first. if a[i] is greater than largest[0] it means it is largest element of array if not then we check with largest[1] which is second largest and so on.

Time complexity -

lines 2,4,7,8,9,10,11,12,13 all are constant time operations because just they are either variable declaration or some condition checking. But line 5 contains a loop in which i range fro 1 to n. which means inner statement executes n times . so let all inner statement executes in c time and other constant operations outside loop executes k times here c and k both are constants.

therefore T(n)= (c+c+c+c...ntimes) +k

T(n) = cn +k

therefore T(n) = O(n)

Add a comment
Know the answer?
Add Answer to:
Derive the worst case big O time to find the 5th largest item in an unsorted...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT