Skip to content

Instantly share code, notes, and snippets.

@ebresafegaga
Last active August 4, 2022 08:35
Show Gist options
  • Save ebresafegaga/b2c12215609e843100f679ec3e902dd7 to your computer and use it in GitHub Desktop.
Save ebresafegaga/b2c12215609e843100f679ec3e902dd7 to your computer and use it in GitHub Desktop.
Counting sort
fn sort<const N: usize>(arr: [i32; N]) -> Vec<i32> {
let mut max = arr[0];
// Find the max of the array
for i in 0..arr.len() {
if arr[i] > max {
max = arr[i]
}
}
// Create a zeroed array with the max
let mut v = vec![0; max as usize];
// Create the frequency table
for elem in arr {
v[elem as usize] += 1;
}
// The actual sorting algorithm
let mut result: Vec<i32> = Vec::new();
for i in 0..v.len() {
let count = v[i];
for _ in 0..count {
result.push(i as i32);
}
}
result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment