How to find max. and min. in array using minimum comparisons?

后端 未结 14 1472
深忆病人
深忆病人 2020-12-04 09:08

This is a interview question: given an array of integers find the max. and min. using minimum comparisons.

Obviously, I can loop over the array twice and use ~

14条回答
  •  生来不讨喜
    2020-12-04 09:23

    if (numbers.Length <= 0)
    {
        Console.WriteLine("There are no elements");
        return;
    }
    
    if (numbers.Length == 1)
    {
        Console.WriteLine($"There is only one element. So min and max of this 
                            array is: {numbers[0]}");
        return;
    }
    
    if (numbers.Length == 2)
    {
        if (numbers[0] > numbers[1])
        {
            Console.WriteLine($"min = {numbers[1]}, max = {numbers[0]}");
            return;
        }
    
        Console.WriteLine($"min = {numbers[0]}, max = {numbers[1]}");
        return;
    }
    
    int i = 0;
    int j = numbers.Length - 1;
    
    int min = numbers[i];
    int max = numbers[j];
    i++;
    j--;
    
    while (i <= j)
    {
        if(numbers[i] > numbers[j])
        {
            if (numbers[j] < min) min = numbers[j];
            if (numbers[i] > max) max = numbers[i];
        }
        else
        {
            if (numbers[i] < min) min = numbers[i];
            if (numbers[j] > max) max = numbers[j];
        }
        i++;
        j--;
    }
    

    It's a solution written in C#. I find this method of burning the candle at both ends to be a good contender as a solution.

提交回复
热议问题