This may be a very open ended question, but I am learning algorithms for the first time. I have been given the problem "Find two largest elements in an array with n elements in 1.5n comparisons". I have to start by designing an algorithm, but I am not sure where or how to begin?
If a value is greater than the second greatest but not the first greatest then your algorithm won't set the second greatest to it since you only test if it's greater than the first greatest.
And I don't think initializing them both to a[0] is correct, either. It's probably best to initialize them to INT_MIN.
n elements in 1.5n comparisons
^^
Should be able to do it in N (-1 whatever) which you already knew when asked directly. the question is flawed.
the code snips are nice but not tied to an algorithm. An algorithm does not care about code, language, data types, etc... its just the steps you will take.
when you find one bigger than largest, move (old) largest to next largest first, then replace largest. no comparison required to do that.
I already explained why that is wrong. You can't just compare to the largest. What if a value is larger than the second largest but not larger than the first largest? That's why it takes more than n, although it usually takes closer to 1.1n than 1.5n. But as lastchance said it's basically between n and 2n, so apparently 1.5n is some kind of average.
The algorithm compares the current value to the second largest and if it's larger than that then compares it to the first largest.
1 2 3 4 5 6
if val > next_largest:
if val > largest:
next_largest = largest
largest = val
else
next_largest = val