Home > Net >  Delphi sorting with 2 while loops, need to get rid of a variable
Delphi sorting with 2 while loops, need to get rid of a variable

Time:06-06

Good morning, couldn't recover my old account so here's the new one. I'm following lessons for Lazarus/Delphi development and one assignement is about sorting an array of integers using 2 nested loops (no functions allowed). Here's my working solution, but they asked me to get rid of the "k" variabile since it's not needed. I cannot figure out how to do it because "j" has a value of 4 at the end of the first loop, I need it to be 1 at the start of the second but if I assign it a value of 0 after the first begin (instead of "j := k;" "j := 1;" it get to 2 at the end of the loop and back to 1 at the start. I thought that a third integer variable could be the solution, start at 1, increase it in the loop, at the start of the loop give "j" the value of "k", but they don't like this.

i := 0;
j := 1;
k := 1;

while i < 4 do
begin
    j := k;
    while j < 5 do
        begin
        if nArray[j] < nArray[i] then
            begin
            tmp := nArray[j];
            nArray[j] := nArray[i];
            nArray[i] := tmp;
            end;
        j := j   1;
        end;
     k := k 1;
     i := i 1;
end;

CodePudding user response:

Have you noticed: k always has the value of i 1. k is initialized to 1 while i is initialized to 0, and both are incremented at the same time. This means you can replace k with i 1.

So j := k would be j := i 1.

  • Related