unit UnsortF;
//*******************************************************
// Example program demonstrating unsorting.
//*******************************************************
// Copyright (C) 1998 John Wiley & Sons, Inc.
// All rights reserved. See additional copyright
// information in Readme.txt.
//*******************************************************

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  Menus, StdCtrls;

type
  TIntArray = array [1..1000000] of Integer;
  PIntArray = ^TIntArray;

  TUnsortForm = class(TForm)
    MainMenu1: TMainMenu;
    File1: TMenuItem;
    mnuExit: TMenuItem;
    Help1: TMenuItem;
    mnuAbout: TMenuItem;
    CmdGo: TButton;
    Label1: TLabel;
    NumItemsText: TEdit;
    ScrollBox1: TScrollBox;
    ScrollBox2: TScrollBox;
    SortedLabel: TLabel;
    UnsortedLabel: TLabel;
    procedure FormCreate(Sender: TObject);
    procedure mnuExitClick(Sender: TObject);
    procedure mnuAboutClick(Sender: TObject);
    procedure CmdGoClick(Sender: TObject);
    procedure RandomizeList(list : PIntArray; min, max : Integer);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  UnsortForm: TUnsortForm;

implementation

{$R *.DFM}

procedure TUnsortForm.FormCreate(Sender: TObject);
begin
    Randomize;
end;

procedure TUnsortForm.mnuExitClick(Sender: TObject);
begin
    Close;
end;

procedure TUnsortForm.mnuAboutClick(Sender: TObject);
const
    CRCR = #13#10#13#10;
begin
    MessageDlg(
        'This program randomizes the items in a list.' + CRCR +
        'Specify the number of items the list should contain and click the Go button. The program will create the list and display it sorted and randomly arranged.'
        , mtInformation, [mbOK], 0);
end;

// Create the list and randomize it.
procedure TUnsortForm.CmdGoClick(Sender: TObject);
const
    CR = #13#10;
var
    i, num_items : Integer;
    list         : PIntArray;
    txt          : String;
begin
    // Allocate space for the list.
    num_items := StrToInt(NumItemsText.Text);
    GetMem(list, num_items * SizeOf(Integer));

    // Initialize the list.
    txt := '';
    for i := 1 to num_items do
    begin
        txt := txt + IntToStr(i) + CR;
        list^[i] := i;
    end;
    SortedLabel.Caption := txt;

    // Randomize.
    RandomizeList(list, 1, num_items);

    // Display the randomized list.
    txt := '';
    for i := 1 to num_items do
        txt := txt + IntToStr(list^[i]) + CR;
    UnsortedLabel.Caption := txt;
end;

// Randomize an array.
procedure TUnsortForm.RandomizeList(list : PIntArray; min, max : Integer);
var
    i, range, pos, tmp : Integer;
begin
    range := max - min + 1;
    for i := min to max - 1 do
    begin
        pos := min + Trunc(Random(range));
        tmp := list^[pos];
        list^[pos] := list^[i];
        list^[i] := tmp;
    end;
end;

end.
