-
-
Notifications
You must be signed in to change notification settings - Fork 63
Added countingsort.lua #38
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
Changes from 2 commits
b77dacd
593d66b
2be6f6b
c08bc1a
a3c6be4
fbd5c22
9f471ae
39e5284
495b01c
dbf28e9
b73ddb6
b6c98e9
585cf1d
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
function counting_sort(arr, key_function) | ||
-- If no key_function is provided, use identity function | ||
key_function = key_function or function(x) return x end | ||
|
||
-- Step 1: Find the range of keys (min_key and max_key) | ||
|
||
local min_key, max_key = math.huge, -math.huge | ||
for i = 1, #arr do | ||
local key = key_function(arr[i]) | ||
if key < min_key then | ||
min_key = key | ||
end | ||
if key > max_key then | ||
max_key = key | ||
end | ||
end | ||
|
||
-- Step 2: Initialize the count array | ||
local count = {} | ||
for i = min_key, max_key do | ||
|
||
count[i] = 0 | ||
end | ||
|
||
-- Step 3: Count the occurrences of each key. In this case key is same as arr[i] | ||
|
||
for i = 1, #arr do | ||
|
||
local key = key_function(arr[i]) | ||
count[key] = count[key] + 1 | ||
end | ||
|
||
-- Step 4: Compute cumulative counts to get final positions | ||
for i = min_key + 1, max_key do | ||
count[i] = count[i] + count[i - 1] | ||
end | ||
|
||
-- Step 5: Build the output array (in stable order) | ||
local output = {} | ||
for i = #arr, 1, -1 do | ||
local element = arr[i] | ||
local key = key_function(element) | ||
output[count[key]] = element | ||
count[key] = count[key] - 1 | ||
end | ||
|
||
-- Step 6: Copy the output array back to the original array | ||
for i = 1, #arr do | ||
arr[i] = output[i] | ||
end | ||
end | ||
|
||
-- Sample array | ||
|
||
local arr = {100, 2, 2, 8, 3, 10000000, 1} | ||
|
||
-- Simple usage with identity key function | ||
counting_sort(arr) | ||
|
||
-- Print sorted array | ||
for i, v in ipairs(arr) do | ||
print(v) | ||
end |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
return
ed directly forrequire
to work with this as expected rather than polluting globals;arr
tolist
for consistency with the rest of the code.key_function
should have a comment explaining what it does and what it defaults to. Especially since this sorting algorithm has special requirements (keys must be integers).