delphi – 按字母顺序排列数组?
发布时间:2020-12-15 09:11:05 所属栏目:大数据 来源:网络整理
导读:假设我有两个字符串数组,名为’arrayone’和’arraytwo’ 我将如何按字母顺序(从A到Z)排序’arrayone’,同时仍保持与第二个数组的关系. 如果你想知道’arrayone’和’arraytwo’是什么,1有姓氏,2有每个人的年龄.我的最终结果是将它添加到一个richedit. 场景
假设我有两个字符串数组,名为’arrayone’和’arraytwo’
我将如何按字母顺序(从A到Z)排序’arrayone’,同时仍保持与第二个数组的关系. 如果你想知道’arrayone’和’arraytwo’是什么,1有姓氏,2有每个人的年龄.我的最终结果是将它添加到一个richedit. 场景示例: Smith 25 Appleseed 32 Gibbs 45 必须变成: Appleseed 32 Gibbs 45 Smith 25 请不要使用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; 它说不兼容的类型:’字符’和’字符串’ 解决方法
在给出了关于数据结构的建议,并看到了随之而来的挣扎之后,我想把事情做好,并更清楚地解释我的意思.
原始代码有两个基本上没有连接的数组.您可以在一个数组中交换项目,并且很容易忘记为另一个数组执行此操作.在我看来,名字/年龄对真的不应该分开.这导致以下类型声明. type TPerson = record Name: string; Age: Integer; end; 现在你需要持有一个TPerson数组. type TPersonArray = array of TPerson; 为了执行排序,您需要能够比较两个项目并交换它们. 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; 现在我们可以将这一切与冒泡排序结合起来. 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; 现在,如果您想使用更复杂的比较运算符,那么您可以简单地替换Compare.例如,如果您想按年龄排序任何具有相同名称的人,则使用词典比较功能. function Compare(const Person1,Person2.Name); if Result=0 then begin Result := Person2.Age-Person1.Age; end; end; 我已经逐一写了这个答案,这就是你应该如何处理这样一个更大的问题.尝试将其分解为更小的部分,每个部分都是可管理的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |