skip to content

JavaScript: DHTML Shell Sort

 Tweet0 Shares0 Tweets

JavaScript: DHTML Shell Sort

This page demonstrates the Shell Sort algorithm. This appears to be the most efficient algorithm out of the four presented on this site. That may be because of 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.

idcolourrandom
1green383
2blue662
3green864
4red646
5purple533
6green789
7purple303
8green257
9blue792
10blue830
11orange208
12purple672
13red803
14green363
15orange172
16purple414
17red258
18purple495
19yellow416
20purple380
Sort by DESC?

[add rows to TABLE]

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.

< JavaScript

Send a message to The Art of Web:


used only for us to reply, and to display your gravatar.

CAPTCHA

<- copy the digits from the image into this box

press <Esc> or click outside this box to close

Post your comment or question
top