Home > Back-end >  find the closest number (smaller) in a sorted list
find the closest number (smaller) in a sorted list

Time:11-24

I want to find the closest number (smaller) to a specified number in a sorted list of integers.

I have the following code

List<int> list = new List<int> { 2, 5, 7, 10 };
int number = 9;

In the above example the desired result is 7. I do

int closest = list.Aggregate((x,y) => Math.Abs(x-number) < Math.Abs(y-number) ? x : y);

But it returns 10. My list has hundreds of thousands of numbers. The above was just a sample.

CodePudding user response:

As the list is sorted, you can use Array.BinarySearch to get at the relevant location quickly. A bit tricky to evaluate the return value in case you don't hit an element exactly.

List<int> list = new List<int> { 2, 5, 7, 10 };
int number = 1;

var index = Array.BinarySearch(list.ToArray(), number);
if (index < 0)
{
    index = ~index - 1;
    if (index >= 0)
        Console.WriteLine(list[index]);
    else
        Console.WriteLine("less than all elements in the list");
}
else
{
    Console.WriteLine(list[index]);
}

CodePudding user response:

var result = list.Where(x => x < number).LastOrDefault();
  • Related