Search code examples
sortingpascalbubble-sort

Pascal bubble sort print each sorted line


I have my bubble sorting algorithm which works correctly but I want to set it up so it prints each line in the process of the final output(19 lines).I have tried almost everything, but it doesn't print correctly:

program Bubble_Sort;

const N = 20;

var
  d : array[1..N] of integer;
var
  i,j,x : integer;
begin

  randomize;
  for i := 1 to N do d[i] := random(100);
  writeln('Before sorting:'); writeln;
  for i := 1 to N do write(d[i], ' ');
  writeln;

  for j := 1 to N - 1 do
    for i := 1 to N - 1 do
      write(d[i], ' ');
      if d[i] > d[i+1] then 
      begin
        x := d[i]; d[i] := d[i+1]; d[i+1] := x;
      end;


  writeln('After sorting:'); writeln;
  for i := 1 to N do write(d[i], ' ');
  writeln;
end.

Solution

  • The outer loop in the center of your code, the for j ... loop runs for each bubble iteration. That is where you want to output the state of the sorting. Because you thus have more than one statement within that for j ... loop, you must also add a begin .. end pair:

    for j := 1 to N - 1 do
    begin
      //one round of sorting
      //display result so far
    end;
    

    The sorting is ok as you have it, except when you added the write(d[i], ' '); presumably to output the sort result for one iteration, you changed the execution order to become totally wrong. Remove the write(d[i], ' '); from where it is now.

    To display the sorting result after each iteration add a new for k ... loop and a writeln;

    for k := 1 to N do
      write(d[k], ' ');
    writeln;
    

    Final sorting and progress display should be structured like:

    for j := 1 to N - 1 do
    begin
      for i := 1 to N - 1 do
      // one round of sorting
      for k := 1 to N - 1 do
      // output result of one sorting round
    end;