冒泡法排序——靜態一維數組

感謝《[Delphi.7應用教程].童愛紅.文字版.pdf》提供的題目、解題方法及文字源程序!本文作者據此轉換爲Delphi源程序(爲方便愛好者學習,程序界面略有修改,源程序包請見附件):

unit SL421;

interface

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

type
  TForm1 = class(TForm)
    GroupBox1: TGroupBox;
    Image1: TImage;
    GroupBox2: TGroupBox;
    Memo1: TMemo;
    GroupBox3: TGroupBox;
    Label1: TLabel;
    Label2: TLabel;
    Edit1: TEdit;
    Edit2: TEdit;
    Button1: TButton;
    Button2: TButton;
    GroupBox4: TGroupBox;
    Memo2: TMemo;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Only_Num(Sender: TObject; var Key: Char);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation
var
  num:Array[1..10] of Integer; //定義一個單元級數組變量,存儲輸入的10個數

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject); //【輸入】按鈕代碼
var
  m:integer;
begin
  edit1.text:='';
  edit2.text:='';
  for m:=1 to 10 do
    begin
      num[m]:=StrToInt(InputBox('請輸入10個整數','輸入第'+IntToStr(m)+'個整數','0'));
      edit1.text:=edit1.text+IntToStr(num[m])+' ,'
    end;
  edit1.text:=copy(edit1.text,1,Length(edit1.text)-1);
   //文件框的文本取從第1個字符起,到除了最後1個字符之外的所有字符
end;

procedure TForm1.Button2Click(Sender: TObject);
Var
  i,j,k,n:integer;
begin
  for i:=1 to 9 do
    begin
      k:=10-i ;  //第i輪比較10-i次
      for j:=1 to k do
        begin
          if num[j]>num[j+1] then   //如果num[j]>num[j+1]就交換兩數
            begin
              n:=num[j];
              num[j]:=num[j+1];
              num[j+1]:=n;
            end;

        end;
    end;
   for i:=1 to 10 do
     edit2.Text:=edit2.text+IntToStr(num[i])+' ,';
   edit2.Text:=copy(edit2.text,1,length(edit2.text)-1);
end;

procedure TForm1.Only_Num(Sender: TObject; var Key: Char);
begin
  if not (key in['0'..'9',#8]) then key:=#13;    //文本框只能輸入數字
end;

end.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章