...

/

Solution: Search Position

Solution: Search Position

Learn how to find an appropriate position to insert a new element in a sorted array.

Solution: Modified binary search

using System;
class Program
{
/// <summary>
/// A mehod to search the insert position of a given value in a array.
/// </summary>
/// <param name="arr">An array of integers.</param>
/// <param name="value">An integer.</param>
/// <returns>The position where the value should be inserted in the array.</returns>
public static int SearchInsertPosition(int[] arr, int value)
{
int size = arr.Length;
if (size < 1)
{
return -1;
}
int start = 0;
int end = size - 1;
int pos = 0;
while (start <= end)
{
int mid = start + (end - start) / 2;
if (arr[mid] == value)
{
return mid;
}
else if (arr[mid] > value)
{
end = mid - 1;
pos = mid;
}
else
{
start = mid + 1;
pos = mid + 1;
}
}
return pos;
}
// Driver to test above code
public static void Main()
{
int[] array = { 1, 3, 5, 6 };
int value = 5;
Console.WriteLine(SearchInsertPosition(array, value));
value = 2;
Console.WriteLine(SearchInsertPosition(array, value));
}
}
...