Pigeonhole sorting is a sorting algorithm that is suitable for sorting lists of elements where the number of elements (n) and the number of possible key values (N) are approximately the same.

Complexity

  • Time:
  • Space:

References

Implementations

  • 1
    
    # TODO: Implement in Python
    
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    
    const A = Randomize.Array1D({ N: 7 });
    const N = A.length;
    
    let min = A[0];
    let max = A[0];
    
    for (let i = 1; i < N; i++) {
      if (A[i] < min) {
        min = A[i];
      }
      if (A[i] > max) {
        max = A[i];
      }
    }
    const range = max - min + 1;
    
    const holes = new Array(range);
    for (let i = 0; i < range; i++) {
      holes[i] = [];
    }
    
    logTracer.println('Filling up holes');
    
    for (let i = 0; i < N; i++) {
    
      holes[A[i] - min].push(A[i]);
    
    }
    
    logTracer.println('Building sorted array');
    
    let k = 0;
    for (let i = 0; i < range; i++) {
      for (let j = 0; j < holes[i].length; j++) {
        
        A[k++] = holes[i][j];
        
      }
    }
    
    logTracer.println(`Sorted array is ${A}`);