[MacRuby-devel] Ruby sort algorithm

Robert Rice rice.audio at pobox.com
Mon Jan 31 20:18:07 PST 2011


Hi Morgan:

Thanks for all your help with the sort algorithm. It occurred to me that in my app I could sort my elements as I create them in my NSXMLParser delegate methods such that I wouldn't need to use a sort algorithm. I now have:

	def add_child( child )
		change		= false
		sequence	= child.sequence
		index		= @children.length
		while index > 0
			break if @children[ index - 1 ].sequence <= sequence
			index	-= 1
			change	= true
		end
		@children.insert( index, child )

		change
	end

btw: For efficiency, I recently converted my app from using REXML to NSXMLDocument and then again to using only NSXMLParser. Using NSXMLParser you can cast the elements as they are parsed directly to your application subclasses rather than to generic NSXMLElement objects. I then write the documents directly from my own XML_Element superclass.
Thus sorting my @children array will correspondingly reformat the XML document when written. It's much easier than sorting XML elements using the  NSXMLElement.previous_sibling= and NSXMLElement .next_sibling= methods.

NSXMLParser has a good usage guide but I could probably save time for anyone interested by posting my XML_Element superclass.

Thanks,
Bob Rice


On Jan 31, 2011, at 3:45 PM, Morgan Schweers wrote:

> Greetings,
> Sorry; I neglected that aspect of your code.
> 
> If, instead of '@children = ...' you were to go:
> 
> 
> def sort_children2
> 
> 
>   new_children = @children.sort_by.with_index { |*args| args}
> 
> 
>   set_modified if @children != new_children
> 
> 
>   @children = new_children
> 
> 
> end
> 
> 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.macosforge.org/pipermail/macruby-devel/attachments/20110131/45094920/attachment.html>


More information about the MacRuby-devel mailing list