How to search insert position of K in a sorted array with Pascal

2 Answers

0 votes
// Given a sorted array/vector/list of distinct integers and a target value K, 
// return the index if the target is found. 
// If not, return the index where it would be if it were inserted in order.

program SearchInsertPosition;

type
  TIntArray = array of Integer;

// Function to find the index of k or the position where it should be inserted
function SearchInsertPositionOfK(arr: TIntArray; k: Integer): Integer;
var
  i: Integer;
begin
  for i := 0 to High(arr) do
  begin
    if arr[i] >= k then
    begin
      Exit(i);
    end;
  end;
  SearchInsertPositionOfK := Length(arr);
end;

var
  arr1, arr2, arr3: TIntArray;
  k1, k2, k3: Integer;

  // initialize dynamic arrays
  SetLength(arr1, 6);
  arr1[0] := 1; arr1[1] := 3; arr1[2] := 5; arr1[3] := 6; arr1[4] := 7; arr1[5] := 8;
  
  k1 := 5;
  writeln(SearchInsertPositionOfK(arr1, k1));

  SetLength(arr2, 6);
  arr2[0] := 1; arr2[1] := 3; arr2[2] := 5; arr2[3] := 6; arr2[4] := 7; arr2[5] := 8;
  
  k2 := 2;
  writeln(SearchInsertPositionOfK(arr2, k2));

  SetLength(arr3, 6);
  arr3[0] := 1; arr3[1] := 3; arr3[2] := 5; arr3[3] := 6; arr3[4] := 7; arr3[5] := 8;
  
  k3 := 9;
  writeln(SearchInsertPositionOfK(arr3, k3));
end.


  
(*
run:
  
2
1
6
  
*)

 



answered May 10, 2025 by avibootz
0 votes
// Given a sorted array/vector/list of distinct integers and a target value K, 
// return the index if the target is found. 
// If not, return the index where it would be if it were inserted in order.

program SearchInsertPosition;

type
  TIntArray = array of Integer;

// Function to find the index of k or the position where it should be inserted - Using Binary Search
function SearchInsertPositionOfK(arr: TIntArray; k: Integer): Integer;
var
  left, right, mid: Integer;
begin
  left := 0;
  right := High(arr);

  while left <= right do
  begin
    mid := left + (right - left) div 2;

    if arr[mid] = k then
    begin
      Exit(mid);
    end
    else if arr[mid] > k then
    begin
      right := mid - 1;
    end
    else
    begin
      left := mid + 1;
    end;
  end;

  SearchInsertPositionOfK := left;
end;

var
  arr1, arr2, arr3: TIntArray;
  k1, k2, k3: Integer;
begin
  // Initialize arrays dynamically
  SetLength(arr1, 6);
  arr1[0] := 1; arr1[1] := 3; arr1[2] := 5; arr1[3] := 6; arr1[4] := 7; arr1[5] := 8;
  
  k1 := 5;
  writeln(SearchInsertPositionOfK(arr1, k1));

  SetLength(arr2, 6);
  arr2[0] := 1; arr2[1] := 3; arr2[2] := 5; arr2[3] := 6; arr2[4] := 7; arr2[5] := 8;
  
  k2 := 2;
  writeln(SearchInsertPositionOfK(arr2, k2));

  SetLength(arr3, 6);
  arr3[0] := 1; arr3[1] := 3; arr3[2] := 5; arr3[3] := 6; arr3[4] := 7; arr3[5] := 8;
  
  k3 := 9;
  writeln(SearchInsertPositionOfK(arr3, k3));
end.



  
(*
run:
  
2
1
6
  
*)

 



answered May 10, 2025 by avibootz
...