Skip to content

Commit 593d66b

Browse files
authored
Update countingsort.lua
1 parent b77dacd commit 593d66b

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

src/sorting/countingsort.lua

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,58 @@
1+
function counting_sort(arr, key_function)
2+
-- If no key_function is provided, use identity function
3+
key_function = key_function or function(x) return x end
14

5+
-- Step 1: Find the range of keys (min_key and max_key)
6+
local min_key, max_key = math.huge, -math.huge
7+
for i = 1, #arr do
8+
local key = key_function(arr[i])
9+
if key < min_key then
10+
min_key = key
11+
end
12+
if key > max_key then
13+
max_key = key
14+
end
15+
end
16+
17+
-- Step 2: Initialize the count array
18+
local count = {}
19+
for i = min_key, max_key do
20+
count[i] = 0
21+
end
22+
23+
-- Step 3: Count the occurrences of each key. In this case key is same as arr[i]
24+
for i = 1, #arr do
25+
local key = key_function(arr[i])
26+
count[key] = count[key] + 1
27+
end
28+
29+
-- Step 4: Compute cumulative counts to get final positions
30+
for i = min_key + 1, max_key do
31+
count[i] = count[i] + count[i - 1]
32+
end
33+
34+
-- Step 5: Build the output array (in stable order)
35+
local output = {}
36+
for i = #arr, 1, -1 do
37+
local element = arr[i]
38+
local key = key_function(element)
39+
output[count[key]] = element
40+
count[key] = count[key] - 1
41+
end
42+
43+
-- Step 6: Copy the output array back to the original array
44+
for i = 1, #arr do
45+
arr[i] = output[i]
46+
end
47+
end
48+
49+
-- Sample array
50+
local arr = {100, 2, 2, 8, 3, 10000000, 1}
51+
52+
-- Simple usage with identity key function
53+
counting_sort(arr)
54+
55+
-- Print sorted array
56+
for i, v in ipairs(arr) do
57+
print(v)
58+
end

0 commit comments

Comments
 (0)