假设我有两个字符串数组,名为'arrayone'和'arraytwo'我将如何按字母顺序(从A到Z)排序'arrayone',同时仍保持与第二个数组的关系.
如果你想知道'arrayone'和'arraytwo'是什么,1有姓氏,2有每个人的年龄.我的最终结果是将它添加到一个richedit.
场景示例:
Smith 25
Appleseed 32
Gibbs 45
Run Code Online (Sandbox Code Playgroud)
必须变成:
Appleseed 32
Gibbs 45
Smith 25
Run Code Online (Sandbox Code Playgroud)
请不要使用stringlist,将其保存在简单的数组和过程中.
更新:我切换到记录.
尝试这个代码没有用
for i := 0 to 26 do
for j := 0 to 26 do
if recordname.surname[j] > recordname.surname[j+1] then begin
line := recordname.surname[j];
line[j] := recordname.surname[j+1];
recordname.surname[j+1] := line;
end;
Run Code Online (Sandbox Code Playgroud)
它说不兼容的类型:'字符'和'字符串'
Dav*_*nan 17
在给出了关于数据结构的建议,并看到了随之而来的挣扎之后,我想把事情做好,并更清楚地解释我的意思.
原始代码有两个基本上没有连接的数组.您可以在一个数组中交换项目,并且很容易忘记为另一个数组执行此操作.在我看来,名字/年龄对真的不应分开.这导致以下类型声明.
type
TPerson = record
Name: string;
Age: Integer;
end;
Run Code Online (Sandbox Code Playgroud)
现在你需要保持一个数组TPerson
.
type
TPersonArray = array of TPerson;
Run Code Online (Sandbox Code Playgroud)
为了执行排序,您需要能够比较两个项目并交换它们.
function Compare(const Person1, Person2: TPerson): Integer;
begin
Result := CompareText(Person1.Name, Person2.Name);
end;
procedure Swap(var Person1, Person2: TPerson);
var
temp: TPerson;
begin
temp := Person1;
Person1 := Person2;
Person2 := temp;
end;
Run Code Online (Sandbox Code Playgroud)
现在我们可以将这一切与冒泡排序结合起来.
procedure Sort(var People: TPersonArray);
var
i, n: Integer;
Swapped: Boolean;
begin
n := Length(People);
repeat
Swapped := False;
for i := 1 to n-1 do begin
if Compare(People[i-1], People[i])>0 then begin
Swap(People[i-1], People[i]);
Swapped := True;
end;
end;
dec(n);
until not Swapped;
end;
Run Code Online (Sandbox Code Playgroud)
现在,如果您想使用更复杂的比较运算符,那么您可以简单地替换Compare
.例如,如果您想按年龄排序任何具有相同名称的人,则使用词典比较功能.
function Compare(const Person1, Person2: TPerson): Integer;
begin
Result := CompareText(Person1.Name, Person2.Name);
if Result=0 then begin
Result := Person2.Age-Person1.Age;
end;
end;
Run Code Online (Sandbox Code Playgroud)
我已经逐一写了这个答案,这就是你应该如何处理这样一个更大的问题.尝试将其分解为更小的部分,每个部分都是可管理的.
归档时间: |
|
查看次数: |
11069 次 |
最近记录: |