var i = 0;
$(document).ready(myFunction);
function myFunction()
{
$('<table id="table" width="100" height="100" border="1"></table>')
.appendTo('body')
.bind('click',myclick);
$("#sortASC").click(function(){
SortArray.array = $("#table tr");
SortArray.sortAsc(0,$("#table tr").length-1);
$("#table tr").detach();
$.each(SortArray.array,function(){
$("#table").append(this);
})
});
$("#sortDESC").click(function(){
SortArray.array = $("#table tr");
SortArray.sortDesc(0,$("#table tr").length-1);
$("#table tr").detach();
$.each(SortArray.array,function(){
$("#table").append(this);
})
});
}
function myclick(){
$('<tr id="'+(i++)+'"><td>'+(i)+'</td></tr>')
.appendTo($(this));
}
var SortArray={
array:[],
sortDesc:function(low,high){
if(low<high){
var middle = this.getMiddleDESC(low,high);
this.sortDesc(0,middle -1);
this.sortDesc(middle +1,high);
}
},
sortAsc: function(low,high){
if(low<high){
var middle = this.getMiddleASC(low,high);
this.sortAsc(0,middle -1);
this.sortAsc(middle +1,high);
}
},
getMiddleDESC:function(low,high){
var temp = this.array[low];
while(low<high){
while(low<high && parseInt($(this.array[low]).attr("id")) > parseInt($(this.array[high]).attr("id"))){
high--;
}
this.array[low] = this.array[high];
while(low<high && parseInt($(this.array[low]).attr("id")) <= parseInt($(this.array[low]).attr("id"))){
low++;
}
this.array[high] = this.array[low];
}
this.array[low] = temp;
return low;
},
getMiddleASC: function(low,high){
var temp = this.array[low];
while(low<high){
while(low<high && parseInt($(this.array[low]).attr("id")) < parseInt($(this.array[high]).attr("id"))){
high--;
}
this.array[low] = this.array[high];
while(low<high && parseInt($(this.array[low]).attr("id")) >= parseInt($(this.array[low]).attr("id"))){
low++;
}
this.array[high] = this.array[low];
}
this.array[low] = temp;
return low;
}
}
<div class="clickme">Click here</div>
<input id="sortASC" type="button" value="升序" />
<input id="sortDESC" type="button" value="降序" />