I have two solution in mind:
The first one is the naive one in which we can sort an array in O(n*log(n)) time and after that we just take the last three elements and return it.
The second one is just to sort the element up to 3 element using bubble sort so we can get three largest value on the right side and return the array . But my doubt is what is the time complexity according to you. From my point of view it is F(n) = 3n (neglecting the constants). Kindly let me know
I think you got it, the worst case is 3n. In "normal" bubble sort you have to make n compares n times hence the O(n^2) to get all elements sorted. In your case, since bubble sort has a side effect of having the largest element being sorted out first and you only need 3 of those, then you would at worst have to make n compares 3 times.
I don't know how to answer your question with log(n) thingy. But in my mind, sorting the source array is not required.
What I would do:
Not sure if it's better than sorting the source array though.
first = second = third = -β
a) Let current array element be x.
b) If (x > first)
{
// This order of assignment is important
third = second
second = first
first = x
}
c) Else if (x > second)
{
third = second
second = x
}
d) Else if (x > third)
{
third = x
}
Please Let me know if you have any queries, will be happy to help π
Vikas Poonia
A beginner level engineer.
TheSheriff
Co-Founder, Founder, Entrepreneur & Problem Solver
Could have a look at the following. They aren't solutions to your problem but are good for understanding different sorts quickly and also playing around with creating some.
visualgo.net/en/sorting
sorting.at