Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add median #19

Merged
merged 3 commits into from
Nov 26, 2023
Merged

Add median #19

merged 3 commits into from
Nov 26, 2023

Conversation

vil02
Copy link
Member

@vil02 vil02 commented Nov 24, 2023

This PR adds a function computing the median (in the naive/basic way).

@vil02 vil02 marked this pull request as ready for review November 24, 2023 23:53
@appgurueu
Copy link
Collaborator

It should be possible to do this in (expected) linear time - without a much more complex implementation - by reusing the existing quickselect implementation, specifically the one using median of medians if you want guaranteed linear time (see here for an example usage of quickselect using median of medians).

To use this, you'd probably want to first shallowcopy the array (since quickselect mutates it).

Then the case of an odd number of elements would be easy enough: Just local i = quickselect(copy, math.ceil(#copy / 2)); return copy[i].
For an even number of elements, you'd still do local i = quickselect(copy, math.ceil(#copy / 2)). Since this partitions copy, you can now do local j = quickselect(copy, 1, nil, i + 1), to get the next largest element after the middle element to the right. (You could of course also just save the element at copy[i], then do a local j = quickselect(copy, #copy/2 + 1)).

@vil02
Copy link
Member Author

vil02 commented Nov 25, 2023

My original plan was to add median.lua and quick_median.lua. I overlooked the fact that the second one it is basically implemented. I will update this PR.

@appgurueu
Copy link
Collaborator

Changed {unpack(list)} to a loop because unpack(list) puts the items on the stack, which is problematic for large lists (the stack is limited and can overflow; on 5.1 / JIT it's pretty "small", about 16k / 65k). Also removed the else since it is redundant with the early return.

@appgurueu appgurueu merged commit e823618 into TheAlgorithms:main Nov 26, 2023
3 checks passed
@vil02 vil02 deleted the add_median branch November 26, 2023 21:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants