C# C# Collections Lists Searching Sorted Lists

status 401
status 401
14,144 Points

questions about a line of code

Hi treehouse community :] someone can explain to me this piece of code?

 students.Insert((-index)-1, newStudent);

Why excatly we need to use Insert and i didnt fully understand why we negate the index

3 Answers

Steven Parker
Steven Parker
171,327 Points

Using "Insert" allows you to add at any point in the list, not just at the end.

The "index" here was just determined to be negative, so negating it makes it positive.


Update: The negative index is the result of calling "BinarySearch". When the search fails, it returns the bitwise complement (which will be a negative number) of the index of the next element that is larger than the searched item. By negating that value and subtracting one, you get the position where you can insert the new item and keep the list in order.

status 401
status 401
14,144 Points

i dont understand the reason for using negative index in this example

int index = students.BinarySearch(newStudent);
            //if the newStudent not in the list
            if(index < 0)
            {
                //we add him.
                students.Insert((-index)-1, newStudent);
            }

where exactly i put the newStudent in the students list?, that's what i couldn't figure out.

status 401
status 401
14,144 Points

By any chance can u give an example with code?

Steven Parker
Steven Parker
171,327 Points

I'm not sure what you mean. The code is already there, you were asking why it negates the value. To recap, it takes the negative value from "BinarySearch" and converts it to the positive value needed by "Insert".