I have implemented a HTML table sorting. I actually implemented a sort first using jQuery and then modified it based on the answer to this question for performance as I had done the same mistake. My question is how to make sure if the code I have written is stable or not?
I know that the stability of sorting depends on the sort method's algorithm and that changes with the browser, and according to this page, mozilla's implementation of sorting is stable, but when I checked with my code, it doesn't seem to be stable. Could someone have a look at my code and let me know how to determine whether the sort performed is stable or not?
<html><head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
asc = new Array();
for (var a=0;a<$("tbody tr:eq(0) td").length;a++) asc[a] = 1;
$("th").click(
function(){
c = $(this).index();
var rows = $("tbody tr");
var rlen = rows.length;
var arr = new Array();
var cols;
for(var i=0;i<rlen;i++){
cols = $("tbody tr:eq("+i+") td");
var clen = cols.length;
arr[i] = new Array();
for (var j=0;j<clen;j++){
arr[i][j] = $("tbody tr:eq("+i+") td:eq("+j+")").html();
}
}
arr.sort(function(a,b){
if (a[c]==b[c]) return 0;
else if(a[c]<b[c]) return -1 * asc[c];
else return asc[c];
});
for (var i=0;i<rlen;i++){
arr[i] = "<td>" + arr[i].join("</td><td>") + "</td>"
}
$("tbody").html("<tr>"+arr.join("</tr><tr>")+"</tr>");
asc[c] = (asc[c]==1)?-1:1;
});});
</script>
<style type="text/css">
table { border-collapse: collapse; border: none;}
th,
td {
border: 1px solid black;
padding: 4px 16px;
font-family: Times New Roman;
font-size: 24px;
text-align: left;
}
th {
background-color: #D8D8D8;
cursor: pointer;
}
</style>
</head><body>
<table>
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tbody>
<tr>
<td>March</td>
<td>180</td>
</tr>
<tr>
<td>January</td>
<td>100</td>
</tr>
<tr>
<td>February</td>
<td>80</td>
</tr>
<tr>
<td>Januray</td>
<td>40</td>
</tr>
<tr>
<td>March</td>
<td>200</td>
</tr>
<tr>
<td>February</td>
<td>90</td>
</tr>
</tbody>
</table>
</body></html>
And if there can be any improvements for efficiency, can anyone point that out as well?