16,748
社区成员
发帖
与我相关
我的任务
分享
procedure TForm1.Button1Click(Sender: TObject);
var
tmp1 : array of array[1..2] of integer; //原来有数据,利用二维数组记录数据及下标
tmp2 : array of array[1..2] of integer; //排序后数据,利用二维数组记录数据新下标
i,j:integer;
t,t1:integer;
begin
if Memo1.Lines.Count <=0 then exit;
SetLength( tmp1, Memo1.Lines.Count); //按Memo1.Lines.Count设置数组长度
SetLength( tmp2, Memo1.Lines.Count);
for i:=0 to Memo1.Lines.Count-1 do //利用Memo1进行数据初始化tmp1,tmp2
begin
tmp1[i,1] := strtoint(Memo1.Lines[i]);
tmp1[i,2] := i;
tmp2[i,1] := strtoint(Memo1.Lines[i]);
tmp2[i,2] := i;
end;
for i:= Memo1.Lines.Count-1 downto 0 do //利用冒泡法进行排序
begin
for j:=0 to i do
begin
if tmp2[j,1]=0 then continue ; //进行比较时,若比较值为0则不进行排序
if tmp2[j+1,1]=0 then //进行比较时,被比较值为0时则与下一个被比较值进行比较
begin
if tmp2[j,1] > tmp2[j+2,1] then ]; // 比较值的大小
begin
t := tmp2[j,1];
t1 := tmp2[j,2];
tmp2[j,1] := tmp2[j+2,1 //进行冒泡
tmp2[j+2,1] := t ;
tmp2[j,2] := tmp2[j+2,2]; //同时更换下标
tmp2[j+2,2] := t1;
end ;
end
else //若比较值和被比较值都不为0则进行比较
begin
if tmp2[j,1] > tmp2[j+1,1] then //同上
begin
t := tmp2[j,1];
t1 := tmp2[j,2];
tmp2[j,1] := tmp2[j+1,1]; //同上
tmp2[j+1,1] := t ;
tmp2[j,2] := tmp2[j+1,2];//同上
tmp2[j+1,2] := t1;
end;
end;
end;
end;
for i:= 0 to Memo1.Lines.Count-1 do
begin
Memo2.Lines.Add(inttostr(tmp2[i,1])+','+inttostr(tmp2[i,2]) );//输出排序后数据,
tmp1[tmp2[i,2],2] := i; //反向查找原有数据在排序后数据中的下标
end;
for i:= 0 to Memo1.Lines.Count-1 do
begin
Memo3.Lines.Add(inttostr(tmp1[i,1])+','+inttostr(tmp1[i,2]) ); //输出原有数据在排序后的下标
end;
end;