Vilmis Neviera Vilmis Neviera - 12 days ago 7
Pascal Question

Pascal, explain me how this loop work

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;


This is the loop from my pascal programming book, and this Procedure should arrange an array from the biggest to smallest, the array is in .txt file and there's already another procedure to read it (N is the lenght of an array). I don't understand how this loop work :( Can you explain me ? (First time asking here, please don't judge)

Answer

There is an error in your algorithm.
The line with j := h; should do the opposite. h is the index with the highest value in the array, counted from where i starts. So when the inner loop is done, index h points to the largest value. After that, you will see a swap of the array between pos i and h, so that D[i] has the largest value.

Next inner loop starts 1 position after the previous, and repeats until the next largest value is found and put into correct position in the array. And so on.

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;