delphi 使用泛型的 TArray 为动态数组排序  
官方Delphi 学习QQ群: 682628230(三千人)\n
频道

delphi 使用泛型的 TArray 为动态数组排序


unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    Memo1: TMemo;
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses Generics.Collections; {引用泛型单元}

{给字符串数组排序}
procedure TForm1.Button1Click(Sender: TObject);
var
  arr: array of string;
  i: Integer;
begin
  {设置动态数组大小}
  SetLength(arr, Memo1.Lines.Count);

  {复制 Memo1 中的文本到数组}
  for i := 0 to Memo1.Lines.Count - 1 do arr[i] := Memo1.Lines[i];

  {排序}
  TArray.Sort(arr);

  {在 Memo1 中查看数组中的数据}
  Memo1.Clear;
  for i := 0 to Length(arr) - 1 do Memo1.Lines.Add(arr[i]);
end;

{给整数数组排序}
procedure TForm1.Button2Click(Sender: TObject);
const
  num = 10;
var
  arr: array of Integer;
  i: Integer;
begin
  SetLength(arr, num);

  Randomize;
  Memo1.Clear;

  {把 10 个随机数放入数组, 并显示在 Memo1 中}
  for i := 0 to num - 1 do
  begin
    arr[i] := Random(100);
    Memo1.Lines.Add(IntToStr(arr[i]));
  end;

  {排序}
  TArray.Sort(arr);

  {等 1 秒中后查看排序结果}
  Sleep(1000);
  Memo1.Clear;
  for i := 0 to num - 1 do Memo1.Lines.Add(IntToStr(arr[i]));
end;

end.

 
 来源:https://www.cnblogs.com/del/archive/2009/10/09/1579897.html

推荐分享
图文皆来源于网络,内容仅做公益性分享,版权归原作者所有,如有侵权请告知删除!
 

Copyright © 2014 DelphiW.com 开发 源码 文档 技巧 All Rights Reserved
晋ICP备14006235号-8 晋公网安备 14108102000087号

执行时间: 0.054446935653687 seconds