Home > database >  Trying to get a median, given a list. Trying to use toArray. Not sure what is wrong
Trying to get a median, given a list. Trying to use toArray. Not sure what is wrong

Time:11-19

Here's what I have but I don't know why it's wrong:

public static int findMedian(List<int> arr)
    {
        int[] asArray = arr.ToArray();
        int[] arrSorted = Array.Sort(asArray);
        float midIndex = 0;
        int arrLength = arrSorted.Length;
        if (arrLength % 2 == 1)
        {
            midIndex = Math.Ceiling(arrLength / 2);
            return arrSorted[midIndex];
        }
        else
        {
            return (arrSorted[Math.Ceiling(arrLength / 2)]   arrSorted[Math.Floor(arrLength / 2)]) / 2;
        }
    }

It says "Cannot implicitly convert type 'void' to 'int[]' " but I dont know where the 'void' is coming from.

CodePudding user response:

The error is coming from your int[] arrSorted = Array.Sort(asArray); line, Array.Sort() sorts the array passed into its first parameter, doesn't return anything. So changing the line to just Array.Sort(asArray); should fix it.

  •  Tags:  
  • c#
  • Related