$("ol.commentlist > li").each(function(){
var a = $(this).attr("id");
var b = $("ol.commentlist > li[id='"+a+"']");
var c = $("ol.commentlist > li > div.comment-body div > p a").attr("href");
var d = $("ol.commentlist > li > div.comment-body div > p a[href='"+c+"']");
var e = document.createElement("ul");
var f = $(d).parent().parent().parent().parent();
if("#"+a==c){
$(e).addClass("children").appendTo($(b));
$(f).appendTo(e);
This would do the trick as long as the matching <li> element is right beneath the one it matches.
Is there another way to sort them?