|
<SCRIPT>
function Quicksort(vec, loBound,
hiBound) {
var pivot, loSwap, hiSwap, temp;
// Two items to
sort
if (hiBound - loBound == 1) {
if (vec[loBound]
> vec[hiBound]) {
temp = vec[loBound];
vec[loBound] = vec[hiBound];
vec[hiBound] = temp;
}
return;
}
// Three or more
items to sort
pivot = vec[parseInt((loBound
+ hiBound) / 2)];
vec[parseInt((loBound
+ hiBound) / 2)] = vec[loBound];
vec[loBound] = pivot;
loSwap = loBound + 1;
hiSwap = hiBound;
do {
//
Find the right loSwap
while (loSwap <=
hiSwap && vec[loSwap] <= pivot) loSwap++;
//
Find the right hiSwap
while (vec[hiSwap]
> pivot) hiSwap--;
//
Swap values if loSwap is less than hiSwap
if (loSwap <
hiSwap) {
temp = vec[loSwap];
vec[loSwap] = vec[hiSwap];
vec[hiSwap] = temp;
}
} while (loSwap < hiSwap);
vec[loBound] = vec[hiSwap];
vec[hiSwap] = pivot;
// Recursively
call function... the beauty of quicksort
// 2 or more items
in first section
if (loBound < hiSwap - 1) Quicksort(vec,
loBound, hiSwap - 1);
// 2 or more
items in second section
if (hiSwap + 1 < hiBound) Quicksort(vec,
hiSwap + 1, hiBound);
}
function PrintArray(vec, lo, hi) {
var i;
for (i = lo; i <= hi; i++) document.write(vec[i]
+ "<BR>");
}
// Create an array and stuff some values
in it
var x = new Array(10);
x[0] = 10;
x[1] = 1;
x[2] = 3;
x[3] = 8;
x[4] = 2;
x[5] = 11;
x[6] = 4;
x[7] = 22;
x[8] = 12;
x[9] = 6;
document.write("Here is a
jumbled array:<BR>");
PrintArray(x, 0, 9);
Quicksort(x, 0, 9); //
Sort the array using quicksort
document.write("<BR>Now
the array is sorted!<BR>");
PrintArray(x, 0, 9);
</SCRIPT>
|