Lecture 11: Notes

Some topics from this lecture are also covered in the Introduction to Algorithms textbook:

counting sort

{$mode delphi}
{$r+}

const
  size = 1000;
  
type
  int_array = array of integer;

// Sort an array of values in the range 0 .. (size - 1).
function countingSort(const a: array of integer): int_array;
var
  count: array[0 .. size - 1] of integer;
  b: array of integer;
  i, n: integer;
begin
  for i := 0 to size - 1 do
    count[i] := 0;
  
  for i in a do
    count[i] := count[i] + 1;
    
  n := length(a);
  for i := size - 1 downto 0 do
    begin
      n := n - count[i];
      count[i] := n;
    end;
  
  setLength(b, length(a));  
  for i in a do
    begin
      b[count[i]] := i;
      count[i] := count[i] + 1;
    end;
  
  exit(b);
end;

var
  a: array of integer;
  i: integer;
begin
  setLength(a, 50);
  for i := low(a) to high(a) do
    a[i] := random(size);
  a := countingSort(a);
  for i in a do
    write(i, ' ');
  writeln;
end.

radix sort

{$mode delphi}
{$r+}
{$optimization on}

unit radix_sort;

interface

procedure radixSort(var a: array of integer);

implementation

const
  base = 65536;
  bits = 16;

procedure sortDigit(const a: array of integer; var b: array of integer; d: integer);
var
  count: array[0 .. base - 1] of integer;
  i, x, n: integer;
begin
  for i := 0 to base - 1 do
    count[i] := 0;
  
  for i in a do
    begin
      x := (i shr d) mod base;
      count[x] := count[x] + 1;
    end;
    
  n := length(a);
  for i := base - 1 downto 0 do
    begin
      n := n - count[i];
      count[i] := n;
    end;
    
  for i in a do
    begin
      x := (i shr d) mod base;
      b[count[x]] := i;
      count[x] := count[x] + 1;
    end;
end;

procedure radixSort(var a: array of integer);
var
  b: array of integer;
begin
  setLength(b, length(a));
  sortDigit(a, b, 0);
  sortDigit(b, a, bits);
end;

end.