Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# C# Collections Lists Searching Sorted Lists

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
231,198 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.

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.

For the list: {"A","B","D","E"} If we call the binary search method for "C", since it is not in the list, it will return -3. The '~' bitwise operator will negate the -3 returned (3) and subtract 1 to get 2. This means that the string "C" should be added at index 2. Hence, myList.Insert(2,"C"), to add C at the third position in the list, to maintain the order of the list.

By any chance can u give an example with code?

Steven Parker
Steven Parker
231,198 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".