JavaScript: DHTML Insertion Sort
JavaScript: DHTML Insertion Sort
This page demonstrates the Insertion Sort algorithm.
id | colour | random |
---|---|---|
1 | purple | 505 |
2 | yellow | 874 |
3 | red | 406 |
4 | green | 883 |
5 | green | 773 |
6 | orange | 898 |
7 | blue | 334 |
8 | red | 69 |
9 | purple | 902 |
10 | green | 508 |
11 | blue | 396 |
12 | yellow | 365 |
13 | blue | 697 |
14 | orange | 361 |
15 | orange | 776 |
16 | yellow | 270 |
17 | red | 234 |
18 | green | 145 |
19 | blue | 787 |
20 | green | 855 |
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.
Related Articles - Sorting Algorithms
- DHTML Quick Sort [JAVASCRIPT]
- DHTML Sorting Using OOP [JAVASCRIPT]
- DHTML Sorting Using OOP - Example 1 [JAVASCRIPT]
- DHTML Bubble Sort [JAVASCRIPT]
- DHTML Shell Sort [JAVASCRIPT]
- DHTML Insertion Sort [JAVASCRIPT]
- Sorting Arrays of Arrays [PHP]
- Sorting SimpleXMLElement Object arrays [PHP]
Send a message to The Art of Web:
press <Esc> or click outside this box to close