JavaScript: DHTML Quick Sort
This page demonstrates the Quick Sort algorithm. This is the most advanced algorithm of the four presented, but has some problems w.r.t. speed and the fact that it is not a 'stable' sort (see link at bottom of page for details).
To date we've found the Shell Sort algorithm to be more efficient with small-ish datasets - the kind of data displayed on websites.
Working Demonstration
id | colour | random |
---|---|---|
1 | blue | 912 |
2 | red | 285 |
3 | purple | 128 |
4 | blue | 455 |
5 | green | 827 |
6 | orange | 377 |
7 | purple | 824 |
8 | yellow | 972 |
9 | red | 382 |
10 | purple | 45 |
11 | green | 439 |
12 | red | 763 |
13 | orange | 781 |
14 | blue | 788 |
15 | blue | 513 |
16 | purple | 695 |
17 | yellow | 933 |
18 | red | 24 |
19 | red | 726 |
20 | purple | 741 |
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 Quick Sort, in theory, being much faster:
/* global variables */
var col = 0;
var parent = null;
var items = new Array();
var N = 0;
var quicksort = function(m, n, desc) {
if(n <= m+1) return;
if((n - m) == 2) {
if(compare(get(n-1), get(m), desc)) exchange(n-1, m);
return;
}
i = m + 1;
j = n - 1;
if(compare(get(m), get(i), desc)) exchange(i, m);
if(compare(get(j), get(m), desc)) exchange(m, j);
if(compare(get(m), get(i), desc)) exchange(i, m);
pivot = get(m);
while(true) {
j--;
while(compare(pivot, get(j), desc)) j--;
i++;
while(compare(get(i), pivot, desc)) i++;
if(j <= i) break;
exchange(i, j);
}
exchange(m, j);
if((j-m) < (n-j)) {
quicksort(m, j, desc);
quicksort(j+1, n, desc);
} else {
quicksort(j+1, n, desc);
quicksort(m, j, desc);
}
};
var sortTable = function(tableid, n, desc) {
parent = document.getElementById(tableid);
col = n;
if(parent.nodeName == "TABLE") {
parent = parent.getElementsByTagName("TBODY")[0];
}
if(parent.nodeName != "TBODY") {
return false;
}
items = parent.getElementsByTagName("TR");
N = items.length;
/* quick sort */
quicksort(0, N, desc);
};
Th quick sort algorithm makes use of the get and compare functions presented previously in the Bubble Sort demonstration combined with the exchange function introduced in the Shell Sort demonstration for swapping non-adjacent elements.
All four methods (using OOP) are now available as external javascript files which you can find linked in the article DHTML Sorting Using OOP.
References
Related Articles - Sorting Algorithms
- JavaScript DHTML Insertion Sort
- JavaScript DHTML Shell Sort
- JavaScript DHTML Quick Sort
- JavaScript DHTML Bubble Sort
- JavaScript Sorting Algorithm Comparison
- JavaScript DHTML Sorting Using OOP - Example 1
- JavaScript DHTML Sorting Algorithms
- PHP Sorting Arrays of Arrays
- PHP Sorting SimpleXMLElement Object arrays