28.01.2013

Delphi and Sleepsort

A while ago, someone on 4chan posted a fun sorting algorithm. It is called Sleepsort and is not recommended to be usedin production. However, I thought it would be fun to implement it in Delphi. Here it is (for your amusement):
program Sleepsort;

var
  items: TArray<integer>;
  i: integer;

begin
  randomize;
  writeln('Random: ');
  setlength(items, 25);
  for i := 0 to High(items) do
  begin
    items[i] := random(length(items) * 4);
    write(IntToStr(items[i]) + ' ');
  end;
  writeln;
  writeln('Sorted: ');
  for i := 0 to high(items) do
  begin
     TSortThread.Create(items[i]);
  end;
  readln;
end.
unit uSortThread;

interface

uses
  Classes;

type
  TSortThread = class (TThread)
  private
    fValue : integer;
  protected
    procedure Execute; override;
  public
    constructor Create(n : integer);
  end;

implementation

uses SysUtils;

constructor TSortThread.Create(n: integer);
begin
  inherited Create;
  fValue := n;
end;

procedure TSortThread.Execute;
begin
  sleep(fValue * 333); // artificial slowdown, to make the process visible for the human eye
  write(IntToStr(fValue)+' ');
end;

end. 

Keine Kommentare: