Using Binary Search to Find Insertion Points in an Array RRS feed

  • Question

  • User-431110550 posted


    I need to modify the below code to return the Index of an Insertion Point in a sorted  Array

    for Instance if objArray={1,2,4} and searchObj=3

    the binarysearch function should return 2 as the Index where 3 should be inserted 

    public int binarySearch(Comparable[] objArray, Comparable searchObj)
    int low = 0;
    int high = objArray.length - 1;
    int mid = 0;
    while (low <= high)
    mid = (low + high) / 2;
    if (objArray[mid].compareTo(searchObj) < 0)
    low = mid + 1;
    else if (objArray[mid].compareTo(searchObj) > 0)
    high = mid - 1;
    return mid;
    return -1;


    Wednesday, September 27, 2017 12:28 AM

All replies

  • User303363814 posted

    You forgot to tell us what your problem is.

    Doesn't compile?  Which line?  What is the error?

    Throws an exception at runtime?  Which line of code?  What exception?

    Wrong answer?  What answer do you get?  How do you call the code?

    Something else?

    Wednesday, September 27, 2017 12:38 AM
  • User-1838255255 posted

    Hi AspDeveloperLife,

    According to your description, I know you want to insert the value to the specify position, I think you need use list<> to append it, then convert it to array.  

    List<T>.Insert Method (Int32, T):


    How to Insert an Item into a C# List:


    C# program that uses ToArray:


    Best Regards,

    Eric Du

    Wednesday, September 27, 2017 8:57 AM
  • User-431110550 posted

    Hi Eric,

    The point is to use Binary search because it is much more efficient. 


    Thursday, September 28, 2017 2:18 AM
  • User303363814 posted

    Have you used the debugger?  Which line is the first one to give you an unexpected value?

    Do you have answers to any of my previous requests for information so that I can help you?

    Saturday, September 30, 2017 6:32 AM