桶排序

  1. /// Sort a slice using bucket sort algorithm.
  2. ///
  3. /// Time complexity is `O(n + k)` on average, where `n` is the number of elements,
  4. /// `k` is the number of buckets used in process.
  5. ///
  6. /// Space complexity is `O(n + k)`, as it sorts not in-place.
  7. pub fn bucket_sort(arr: &[usize]) -> Vec<usize> {
  8. if arr.is_empty() {
  9. return vec![];
  10. }
  11. let max = *arr.iter().max().unwrap();
  12. let len = arr.len();
  13. let mut buckets = vec![vec![]; len + 1];
  14. for x in arr {
  15. buckets[len * *x / max].push(*x);
  16. }
  17. for bucket in buckets.iter_mut() {
  18. super::insertion_sort(bucket);
  19. }
  20. let mut result = vec![];
  21. for bucket in buckets {
  22. for x in bucket {
  23. result.push(x);
  24. }
  25. }
  26. result
  27. }
  28. #[cfg(test)]
  29. mod tests {
  30. use super::super::is_sorted;
  31. use super::*;
  32. #[test]
  33. fn empty() {
  34. let arr: [usize; 0] = [];
  35. let res = bucket_sort(&arr);
  36. assert!(is_sorted(&res));
  37. }
  38. #[test]
  39. fn one_element() {
  40. let arr: [usize; 1] = [4];
  41. let res = bucket_sort(&arr);
  42. assert!(is_sorted(&res));
  43. }
  44. #[test]
  45. fn already_sorted() {
  46. let arr: [usize; 3] = [10, 9, 105];
  47. let res = bucket_sort(&arr);
  48. assert!(is_sorted(&res));
  49. }
  50. #[test]
  51. fn basic() {
  52. let arr: [usize; 4] = [35, 53, 1, 0];
  53. let res = bucket_sort(&arr);
  54. assert!(is_sorted(&res));
  55. }
  56. #[test]
  57. fn odd_number_of_elements() {
  58. let arr: Vec<usize> = vec![1, 21, 5, 11, 58];
  59. let res = bucket_sort(&arr);
  60. assert!(is_sorted(&res));
  61. }
  62. #[test]
  63. fn repeated_elements() {
  64. let arr: Vec<usize> = vec![542, 542, 542, 542];
  65. let res = bucket_sort(&arr);
  66. assert!(is_sorted(&res));
  67. }
  68. }