• 0

[VB .NET]Finding Min and Max


Question

5 answers to this question

Recommended Posts

  • 0
  weenur said:

ArrayList.Sort()

dim min as Integer = ArrayList[0]

dim max as Integer = ArrayList[ArrayList.Count - 1]

That's like an O(nlgn) operation. Not very efficient. The most efficient really is just looping through the array once. I'm that very well versed with vb.net so I can't just type the code here, but basically:

1. Set the variables min and max as integers to the first value of the array (position 0).

2. loop through the array. for each element, if it is larger than max, set max = that value. if it is smaller than min, set min = that value

3. when the loop ends, max and min will be the values you are looking for.

  • 0
  Post-It Note said:

That's like an O(nlgn) operation. Not very efficient. The most efficient really is just looping through the array once. I'm that very well versed with vb.net so I can't just type the code here, but basically:

1. Set the variables min and max as integers to the first value of the array (position 0).

2. loop through the array. for each element, if it is larger than max, set max = that value. if it is smaller than min, set min = that value

3. when the loop ends, max and min will be the values you are looking for.

Mistook 'efficient' for simple.

  • 0

Here is how i would do it with looping....

Hope this helps...

Module Module1

	Sub Main()

		Dim numList As New ArrayList

		numList.Add(1)
		numList.Add(5)
		numList.Add(3)
		numList.Add(15)
		numList.Add(25)
		numList.Add(5)

		Console.WriteLine("Maximum: " + DetermineMax(numList).ToString())
		Console.WriteLine("Mininum: " + DetermineMin(numList).ToString())

		Console.ReadKey()

	End Sub

	Public Function DetermineMax(ByVal itemList As ArrayList)

		Dim max As Integer = Nothing

		For i As Integer = 0 To (itemList.Count - 1)
			If i = 0 Then
				max = itemList(i)
			Else
				If itemList(i) > max Then max = itemList(i)
			End If
		Next

		DetermineMax = max

	End Function

	Public Function DetermineMin(ByVal itemList As ArrayList)

		Dim min As Integer = Nothing

		For i As Integer = 0 To (itemList.Count - 1)
			If i = 0 Then
				min = itemList(i)
			Else
				If itemList(i) < min Then min = itemList(i)
			End If
		Next

		DetermineMin = min

	End Function

End Module

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.