Algorithm ADA-我有两个气泡排序算法,但只有一个有效
正如标题所说,我有两种气泡排序算法,但我编写的一种算法并非在所有情况下都有效 这是适用于所有情况的代码Algorithm ADA-我有两个气泡排序算法,但只有一个有效,algorithm,sorting,generics,ada,Algorithm,Sorting,Generics,Ada,正如标题所说,我有两种气泡排序算法,但我编写的一种算法并非在所有情况下都有效 这是适用于所有情况的代码 procedure Sort( t: in out Item_array) is Finished : Boolean; tmp: Item; begin loop Finished := True; for J in t'First..Index'Pred(t'Last) loop if t(J) < t(Index'Succ(J)) then
procedure Sort( t: in out Item_array) is
Finished : Boolean;
tmp: Item;
begin
loop
Finished := True;
for J in t'First..Index'Pred(t'Last) loop
if t(J) < t(Index'Succ(J)) then
Finished := False;
tmp := t(Index'Succ(J));
t(Index'Succ(J)) := t(J);
t(J) := tmp;
end if;
end loop;
exit when Finished;
end loop;
end Sort;
过程排序(t:输入输出项_数组)为
完成:布尔;
tmp:项目;
开始
环
完成:=真;
对于t'First..Index'Pred(t'Last)循环中的J
如果t(J)
这是我的代码,它不适用于以下数组(2,4,3,2,2,5)。我想这是因为多个'2'
procedure Sort( t: in out Item_array) is
I : Index := t'Last;
CS: Index := t'First;
tmp: Item;
begin
while I >= Index'Succ(t'First) loop
for J in t'First..Index'Pred(I) loop
if t(J) < t(Index'Succ(J)) then
tmp := t(Index'Succ(J));
t(Index'Succ(J)) := t(j);
t(j) := tmp;
CS := J;
end if;
end loop;
I := CS;
end loop;
end Sort;
过程排序(t:输入输出项_数组)为
I:索引:=t'Last;
CS:索引:=t'First;
tmp:项目;
开始
而I>=Index'Succ(t'First)循环
对于t'First..Index'Pred(I)循环中的J
如果t(J)
在这两种情况下,“可能是无限循环是由于<代码> Cs<代码>变量在数组被排序之后不改变,因此<代码> < < /代码>永远不会改变吗?您可以考虑更改该行<代码> I:Cs<代码> >代码> I:= SUCC(i)< /代码>。或者应该是代码> PRD(I)< /代码>?无论您走哪条路。(我已经很多年没看Ada了。)@JimMischel你可能是对的!但是我声明为
CS:Index:=t'First
,所以如果数组都排序了,我必须是t'First
,因此while循环应该会中断。你能想出一个更好的CS
名称吗?这个名称解释了它的含义,它的用途。说到这里,I
,似乎很简单尝试一下我的建议。如果它有效,那么您知道问题在于您在该循环中修改I
的方式。我认为您试图使用CS
变量进行某种优化,尽管正如@SimonWright指出的,很难确定。顺便说一句,如果I
等于t'首先
,然后您的循环看起来不会中断,因为您的条件是=
,而不是
。但是,我可能误解了Ada语法。
function Asc(A,B : in Integer) return Boolean is (A > B); // Sorting function
procedure Sort_Asc is new Sort(Item=>Integer,
Index=>Positive,
Item_Array=>Int_Array,
"<"=>Asc);
x : Int_Array := (2,4,3,2,2,5);
Sort_Asc(x);