How to sort an array that consists of only 0s and 1s in Pascal

1 Answer

0 votes
program SortBinaryArray;

const
  N = 9;  // Size of the binary array

type
  IntArray = array[1..N] of integer;

// Function to sort an array containing only 0s and 1s
procedure SortBinaryArray(var arr: IntArray);
var
  left, right, temp: integer;
begin
  left := 1;              // Index to track the left side
  right := N;             // Index to track the right side

  while left < right do
  begin
    // If the left Index is at 0, move it forward
    if arr[left] = 0 then
    begin
      writeln('left: ', left);
      inc(left);
    end
    // If the right Index is at 1, move it backward
    else if arr[right] = 1 then
    begin
      writeln('right: ', right);
      dec(right);
    end
    // If left is 1 and right is 0, swap them
    else
    begin
      temp := arr[left];
      arr[left] := arr[right];
      arr[right] := temp;
      writeln('swap() left: ', left, ' right: ', right);
      inc(left);
      dec(right);
    end;
  end;
end;

var
  arr: IntArray;
  i: integer;

begin
  // Input: Binary array
  arr[1] := 1;
  arr[2] := 0;
  arr[3] := 1;
  arr[4] := 0;
  arr[5] := 1;
  arr[6] := 0;
  arr[7] := 0;
  arr[8] := 1;
  arr[9] := 0;

  // Sort the binary array
  SortBinaryArray(arr);

  // Output the sorted array
  write('Sorted array: ');
  for i := 1 to N do
    write(arr[i], ' ');
end.



(*
run:

swap() left: 1 right: 9
left: 2
right: 8
swap() left: 3 right: 7
left: 4
swap() left: 5 right: 6
Sorted array: 0 0 0 0 0 1 1 1 1 

*)

 



answered Sep 2, 2025 by avibootz
...