JavaScript: DHTML Shell Sort
This page demonstrates the Shell Sort algorithm which appears to be the most efficient algorithm out of the four presented on this site.
That may be due to faults in the implementation of the Quick Sort algorithm (see related link on that page for details), but until that's confirmed you probably want to use the shell sort.
Working Demonstration
id | colour | random |
---|---|---|
1 | blue | 476 |
2 | purple | 194 |
3 | yellow | 301 |
4 | blue | 24 |
5 | yellow | 656 |
6 | red | 974 |
7 | yellow | 834 |
8 | blue | 545 |
9 | green | 78 |
10 | blue | 246 |
11 | red | 38 |
12 | orange | 395 |
13 | green | 265 |
14 | red | 900 |
15 | green | 560 |
16 | yellow | 834 |
17 | purple | 195 |
18 | orange | 289 |
19 | orange | 620 |
20 | purple | 752 |
How does it work?
For a more detailed discussion on the sorting process, you can refer to the Bubble Sort page. The only difference between the two is the actual sorting algorithm, with the Insertion Sort, in theory, being a little bit faster:
// global variables
var col = 0;
var parent = null;
var items = new Array();
var N = 0;
function isort(m, k, desc)
{
for(var j=m+k; j < N; j+= k) {
for(var i=j; i >= k && compare(get(i), get(i-k), desc); i-= k) {
exchange(i, i-k);
}
}
}
function sortTable(tableid, n, desc)
{
parent = document.getElementById(tableid);
col = n;
if(parent.nodeName != "TBODY")
parent = parent.getElementsByTagName("TBODY")[0];
if(parent.nodeName != "TBODY")
return false;
items = parent.getElementsByTagName("TR");
N = items.length;
// shell sort
if((k = Math.floor(N/5)) > 7) {
for(var m=0; m < k; m++) isort(m, k, desc);
}
if((k = Math.floor(N/7)) > 7) {
for(var m=0; m < k; m++) isort(m, k, desc);
}
for(k=7; k > 0; k -= 2) {
for(var m=0; m < k; m++) isort(m, k, desc);
}
}
Interestingly, the Shell Sort algorithm actually makes use of the previously presented Insertion Sort algorithm.
New exchange function
Because the Shell Sort algorithm requires non-adjacent items to be swapped, we need to make some changes to the exchange function that was previously used for both the Bubble Sort and Insertion Sort. The get and compare functions remain unchanged.
function exchange(i, j)
{
if(i == j+1) {
parent.insertBefore(items[i], items[j]);
} else if(j == i+1) {
parent.insertBefore(items[j], items[i]);
} else {
var tmpNode = parent.replaceChild(items[i], items[j]);
if(typeof(items[i]) == "undefined") {
parent.appendChild(tmpNode);
} else {
parent.insertBefore(tmpNode, items[i]);
}
}
}
For an even more advanced sorting technique, see the Quick Sort demonstration.
Related Articles - Sorting Algorithms
- JavaScript DHTML Insertion Sort
- JavaScript DHTML Shell Sort
- JavaScript Sorting Algorithm Comparison
- JavaScript DHTML Sorting Using OOP - Example 1
- JavaScript DHTML Sorting Algorithms
- JavaScript DHTML Quick Sort
- JavaScript DHTML Bubble Sort
- PHP Sorting Arrays of Arrays
- PHP Sorting SimpleXMLElement Object arrays