skip to content

JavaScript: DHTML Insertion Sort

 Tweet0 Shares0 Tweets

JavaScript: DHTML Insertion Sort

This page demonstrates the Insertion Sort algorithm.

idcolourrandom
1blue929
2green837
3blue60
4purple949
5blue483
6green426
7orange800
8blue293
9yellow896
10blue382
11yellow176
12red620
13red460
14blue526
15orange699
16red235
17orange67
18red500
19blue80
20red426
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 parent = null; // 'parent' node var items = new Array(); // array of 'child' nodes var col = 0; // column for sorting 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; // assert: parent is now a TBODY node items = parent.getElementsByTagName("TR"); var N = items.length; // insertion sort for(var j=1; j < N; j++) { for(var i=j; i > 0 && compare(get(i), get(i-1), desc); i--) { exchange(i, i-1); } } }

For more advanced (and complicated) sorting techniques, see the Shell Sort and Quick Sort demonstrations.

< 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