查找整数数组中的最大值
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics;//注意,调试模式 namespace ConsoleApplication4 { class Program { static void Main(string[] args) { int[] testArray ={ 4, 7, 4, 2, 7, 3, 7, 8, 3, 9, 1, 9 }; int[] maxValIndices; int maxVal = Maxima(testArray, out maxValIndices); Console.WriteLine("Maximum value {0} found at element indices", maxVal); foreach (int index in maxValIndices) //列出数组中的元素 { Console.WriteLine(index); } Console.ReadKey(); } static int Maxima(int[] integers, out int[] indices) { Debug.WriteLine("Maximum value search start."); indices=new int[1];//数组长度1 int maxVal=integers[0]; indices[0]=0; int count=1; Debug.WriteLine("Maximum value initilized to" + maxVal + ", at element index 0."); for (int i=1;i<integers.Length;i++) { Debug.WriteLine("Now looking at element at index"+i+"."); if (integers[i]>maxVal) { maxVal=integers[i]; count=1; indices=new int[1]; indices[0]=i;//重新对数组中的元素赋值 Debug.WriteLine("New maximum found. New value is "+maxVal+", at element index "+i+"."); } else { if (integers[i]==maxVal) { count++;//计数器加1 int[] oldIndices=indices; indices=new int[count];//数组长度变化 oldIndices.CopyTo(indices,0);//将旧数组中的元素复制进新的数组,位置从0开始 indices[count-1]=i; Debug.WriteLine("Duplicate maximum found at element index"+i+"."); } } } Trace.WriteLine("Maximum value "+maxVal+" found, with "+count+" occurrences."); Debug.WriteLine("Maximum value search completed."); return maxVal; } } }
暧昧帖
Tags : c#

полезно почитать спасибо.
2009/09/01 17:59 | #1