procedure arranging;
var
i,j,h : integer;
c : real;
begin
for i := 1 to n - 1 do
begin
h := i;
for j := i + 1 to n do
If D[j] > D[h] then
j := h;
c := D[i];
D[i] := D[h];
D[h] := c;
end;
end;
这是我的pascal编程书中的循环,此过程应该从最大到最小的数组安排一个数组,该数组在.txt文件中,并且已经有另一个过程可以读取它(n是数组的lenght)。我不明白这个循环是如何工作的:(您能解释我吗?(第一次问这里,请不要判断)
您的算法中存在错误。
使用j := h;
的线应相反。h
是数组中最高值的索引,从i
启动的位置计数。因此,当完成内部循环时,索引h
指向最大值。之后,您将看到POS i
和h
之间的数组互换,因此D [I]具有最大的价值。
下一个内部循环在上一个后开始1个位置,然后重复直到找到下一个最大的值并将其放在数组中的正确位置。等等。
procedure arranging;
var
i,j,h : integer;
c : real;
begin
for i := 1 to n - 1 do // Loop all values but the last
begin
h := i; // <-- Assume largest value in index i
for j := i + 1 to n do // Loop from i+1 to last value
If D[j] > D[h] then
h := j; // <-- h points to largest array value so far
c := D[i]; // Save D[i] to a temporary storage
D[i] := D[h]; // Now swap values so D[i] has the largest value
D[h] := c;
end;
end;