How to find first and last positions of an element in a sorted array in Pascal

1 Answer

0 votes
program FindFirstAndLastPosition;

type
  TIntArray = array of Integer;

function FindFirstAndLastPosition(arr: TIntArray; n: Integer): TIntArray;
var
  i, first, last: Integer;
begin
  first := -1;
  last := -1;

  for i := 0 to Length(arr) - 1 do
  begin
    if arr[i] <> n then
      Continue;

    if first = -1 then
      first := i;
    last := i;
  end;

  SetLength(FindFirstAndLastPosition, 2);
  FindFirstAndLastPosition[0] := first;
  FindFirstAndLastPosition[1] := last;
end;

var
  arr: TIntArray;
  n: Integer;
  resultArr: TIntArray;
  first, last: Integer;
begin
  // Initialize array
  arr := TIntArray.Create(1, 3, 7, 8, 3, 1, 9);
  n := 3;

  resultArr := FindFirstAndLastPosition(arr, n);
  first := resultArr[0];
  last := resultArr[1];

  if first <> -1 then
    WriteLn('First position = ', first, ' Last position = ', last)
  else
    WriteLn('Not found');
end.


  
/*
run:
  
First position = 1 Last position = 4
  
*/

 



answered 5 days ago by avibootz
...