program bubbleSort;
{*************
Made originally by Ilona Belous, fixed and enriched by Lior Tubi.
This program sorts an integer array to an ascending order, using the bubble-sort algorithm.
**************}

uses crt;
const ARRAYSIZE = 15; {Const array size}
var intArray:array [1..ARRAYSIZE] of integer;
    i, j, temp, flagSorted, numberOfSwaps:integer;
begin
  randomize; {Different numbers each run}
  clrscr; {Clear screen}

  writeln('>> Array size: ', ARRAYSIZE);

  writeln('>> The array: ');
  for i := 1 to ARRAYSIZE do {Initialize and print array with random numbers<1000}
  begin
    intArray[i] := random(1000);
    write(intArray[i], ' ');
  end;
  writeln;
  flagSorted := 0;
  i := 1;
  numberOfSwaps := 0;
  while((i<ARRAYSIZE) and (flagSorted=0)) do
  begin
    flagSorted := 1; {Assume array is sorted}
    for j := 1 to (ARRAYSIZE-i) do
    begin
      if intArray[j] > intArray[j+1] then
      begin
        temp := intArray[j+1];
        intArray[j+1] := intArray[j];
        intArray[j] := temp;
        numberOfSwaps := numberOfSwaps+1;
        flagSorted := 0; {We made a swap, the array might be unsorted}
      end;
    end;
    i := i+1;
  end;

  writeln;
  writeln;
  writeln('>> The sorted array: ');
  for i := 1 to ARRAYSIZE do {Print sorted array}
    write(intArray[i], ' ');
  writeln;
  writeln;
  writeln('>> Number of swaps made: ', numberOfSwaps);
  read(i);

end.
