I know how to find the largest element in the list & mdash; There is no problem, but me second the biggest element?
Say that is the second largest (+ list, val)
and if wall
is the second largest element in the list
If there is a tie for the biggest, then the second largest is ...
One way to do this (n) is first, initially, ( slne / 2
). Given that we are after the second largest element, we will assume that you have the input list (number) with at least two lengths. I first remove the things by comparing the relative values of the two elements and the current maximum And as the current 'second largest' record (as previously suggested, by Priyank), call ( Slne / 4
) to call any other predicate for calling:
Slane ([E0, E1 | Es], res): - E0 & Gt; E1,!, Slen (SE, E., E1, Race). Slane ([E, E1 | AS], Race): - Slane (SE, E1, E., Race). Secondly, now we have got the starting point of the reference, through the rest of the list (if any) and by returning the second largest element (less than MAX), ( Slay / 4
). Base case: No more elements left! We have ended Next case: We can get a new local maximum at the beginning of the list:
Slane ([], _, res, res)
P>
Slane ([E.SE], Max, _SecMax, Res): - E & gt; = Max,!, Slane (SE, E, MAX, race)
(Note that we throw the second second largest (secondend) because we believe that Max is equal to or Was equal to it) Next case: We are not getting a new local maximum, but we find a new 'second best':
Slane ([E.E.S.], Max, SecMax, Ridge): - E & gt;
Final case: Throw down other values, because they are irrelevant - look at the rest instead:
< Pre> slane ([_ | Es], max, cicamax, res): - slen (se, max, cemax, race).
That's it. Personally, I like the solution of Juanjo, mainly because it is a line of code, and the performance difference between o (n log n) and o (n) can also be negligible for large input ( Also keep in mind that dsort / 2
does not appear in all PROLOG implementations - for example, in SWI-PL, you can try msort / 2
instead Are).
No comments:
Post a Comment