I'm looking for general feedback on this implementation. What issues might it have? How could it be improved?
public class FindRunningMedian
{
public void Run(string[] args)
{
var bound = 100000;
var rando = new Random();
var values = new[] { bound.ToString() }.Concat((from i in Enumerable.Range(0, bound)
select rando.Next(int.MaxValue / 2).ToString())).ToArray();
RunBiSect(values);
}
public void RunBiSect(string[] args)
{
var count = Convert.ToInt32(args.First());
var valus = args.Skip(1).Select(s => Convert.ToInt32(s)).ToArray();
var sortd = new MedianList(count);
foreach (var value in valus)
{
Console.WriteLine($"{sortd.InsertForMedian(value):F1} ");
}
}
public class MedianList
{
private int _count;
private float _iters;
private int[] _values;
public MedianList(int capacity)
{
_values = new int[capacity];
}
public int Count { get { return _count; } }
public float Iterations { get { return _iters; } }
public float IterationsPer { get { return _iters / Math.Max(1, _count); } }
public int[] GetValues()
{
var copy = new int[_values.Length];
_values.CopyTo(copy, 0);
return copy;
}
public float InsertForMedian(int value)
{
Insert(value);
var median = 0.0f;
var middle = _count / 2;
if (_count == 1) { median = _values[0]; }
else if (_count % 2 == 0) { median = (_values[middle] + _values[middle - 1]) / 2.0f; }
else { median = _values[middle]; }
return median;
}
public void Insert(int value)
{
if (_count == 0) { _values[0] = value; }
else
{
var index = FindDestinationIndex(value);
Array.Copy(_values, index, _values, index + 1, _count - index);
_values[index] = value;
}
_count++;
}
public int FindDestinationIndex(int value)
{
var max = _count - 1;
int mid = 0, cmp = 0, min = 0;
if (value.CompareTo(_values[0]) <= 0) { return 0; }
else if (value.CompareTo(_values[_count - 1]) >= 0) { return _count; }
while (max > (min + 1))
{
mid = Convert.ToInt32(Math.Min(Math.Ceiling((max - min) / 2.0f) + min, _count - 1));
cmp = value.CompareTo(_values[mid]);
if (cmp == 0) { return mid; }
else if (cmp > 0) { min = Math.Max(mid, min + 1); }
else if (cmp < 0) { max = Math.Min(mid, max - 1); }
_iters++;
}
mid = value.CompareTo(_values[min]) > 0 && value.CompareTo(_values[max]) <= 0 ? max : min;
cmp = value.CompareTo(_values[mid]);
var index = cmp > 0 ? mid + 1 : mid;
return index;
}
}
}
Console.ReadLine()
. For this example, it really could beint[]
and wouldn't have any impact on the bisecting methodFindDestinationIndex
. \$\endgroup\$