查找输入序列中的最大最小数值,要求时间复杂度为1.5n
C#实现如下:
public class MinMaxFinder<T> where T : IComparable<T> { public void FindMinMax(T[] array, int startIndex, int endIndex, out T minValue, out T maxValue) { maxValue = array[startIndex]; minValue = array[startIndex]; if ((endIndex - startIndex + 1) % 2 == 0)//偶数个数据 { for (int i = startIndex; i <= endIndex; i = i + 2) { if (array[i].CompareTo(array[i + 1]) >= 0) { if (array[i].CompareTo(maxValue) > 0) maxValue = array[i]; if (array[i + 1].CompareTo(minValue) < 0) minValue = array[i + 1]; } else { if (array[i + 1].CompareTo(maxValue) > 0) maxValue = array[i + 1]; if (array[i].CompareTo(minValue) < 0) minValue = array[i]; } } } else//奇数个数据 { for (int i = startIndex; i <= endIndex-1; i = i + 2) { if (array[i].CompareTo(array[i + 1]) >= 0) { if (array[i].CompareTo(maxValue) > 0) maxValue = array[i]; if (array[i + 1].CompareTo(minValue) < 0) minValue = array[i + 1]; } else { if (array[i + 1].CompareTo(maxValue) > 0) maxValue = array[i + 1]; if (array[i].CompareTo(minValue) < 0) minValue = array[i]; } } if (array[endIndex].CompareTo(maxValue) > 0) maxValue = array[endIndex]; if (array[endIndex].CompareTo(minValue) < 0) minValue = array[endIndex]; } } }
调用方法:
static void Main(string[] args) { //int[] data = new int[] { 23, 12, 45, 15, 1, 79, 8 }; int[] data = new int[] { 23, 12, 45, 15, 1, 79, 8 ,-1}; var minmaxfinder = new MinMaxFinder<int>(); int min, max; minmaxfinder.FindMinMax(data, 0, data.Length - 1, out min, out max); Console.WriteLine("min:{0} max:{1}", min, max); Console.ReadKey(); }
作者:Andy Zeng
欢迎任何形式的转载,但请务必注明出处。
http://www.cnblogs.com/andyzeng/p/3695372.html