Heres a fairly simple one

rifter1818

Well-known member
Joined
Sep 11, 2003
Messages
255
Location
A cold dark place
Im creating a general sorting algorythm, pretty simple but i want it to be able to sort any array,....
so lets say i have an array of blahs
public structure blah
public x,y as integer
end structure
and i want this array sorted by the xs...
public sub sort(array() as object,subobject as ??????)
if array(i).subobject < array(i+1).subobject then
.......
end if
....
end sub
sorry for the shortened code but the concept is so simple. i just need to know how to pass elemnts to the functions / subs.. Thanks for all your help
 
Is there any reason why you dont want to use the build in Array.Sort? You would just need to implement the IComparable interface.

Code:
Public Structure blah
		Implements IComparable

		Public x, y As Integer

		Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo
			If Not TypeOf obj Is blah Then
				Throw New InvalidOperationException("Can only compare to Blah things")
			End If

			Dim b As blah = DirectCast(obj, blah)
			If Me.x > b.x Then Return 1
			If Me.x < b.x Then Return -1
			Return 0

		End Function
	End Structure

	Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
		Dim arr(4) As blah
		populate arr()
		Dim r As New Random
		arr(0).x = r.Next
		arr(1).x = r.Next
		arr(2).x = r.Next
		arr(3).x = r.Next
		arr(4).x = r.Next

		Array.Sort(arr)
	End Sub
 
The only thing is

That way means i have to program compairtos into every structure, and if i want to sort by xs first then latter sort by ys or sort by xs and then sort by ys the code gets more and more complicated, if i could find a way to send a function which element it is it would be much easyer,.. and would be usefull in other instances which are a bit more complicated
 
Maybe you could create an abstract base class that implements IComparable, and have all other classes inherit from the base? Its possible to build enough logic into the IComparable implementation to cover quite a few different scenarios.

For example, in the past Ive had to sort giant lists of various business objects. Some objects had letters as names, while others used numbers (IP Addresses had to be sorted and obviously couldnt be handled the same way as sorting contacts). It was relatively easy to build the logic into my algorithm to handle several different sorting needs.
 
Last edited by a moderator:
Back
Top