Javascript 2 Dimensional QuickSort

Here is some code I found and modified for a Javascript 2 Dimensional Quicksort. I was using a bubble sort but decided to change over to Quicksort considering I was going to have a huge dataset.

———————————————————

function Quicksort(vec, k){
QuicksortHelp(vec, k, 0, vec[k].length-1);
}

function QuicksortHelp(vec, k, loBound, hiBound){
if (debug)
if (!confirm(loBound + " " + hiBound))
return;
var loSwap, hiSwap, temp;
var pivot = new Array(vec.length);
// Two items to sort
if (hiBound - loBound == 1){
if (vec[k][loBound].toLowerCase() > vec[k][hiBound].toLowerCase())
swap(vec,loBound,hiBound);
return;
}
// Three or more items to sort
for (counter=0; counter < vec.length; counter++){
pivot[counter] = vec[counter][parseInt((loBound + hiBound) / 2)];
vec[counter][parseInt((loBound + hiBound) / 2)] = vec[counter][loBound];
vec[counter][loBound] = pivot[counter];
}
loSwap = loBound + 1;
hiSwap = hiBound;

mycount = 0
do {
if (debug)
if (!confirm(loSwap + " YEA " + hiSwap))
return;
// Find the right loSwap
while (loSwap <= hiSwap && vec[k][loSwap].toLowerCase() <= pivot[k].toLowerCase()){
loSwap++;
}

// Find the right hiSwap
while (vec[k][hiSwap].toLowerCase() > pivot[k].toLowerCase()){
hiSwap--;
}

// Swap values if loSwap is less than hiSwap
if (loSwap < hiSwap)
swap(vec,loSwap,hiSwap);
mycount++;
} while (loSwap < hiSwap);

for (counter=0; counter < vec.length; counter++){
vec[counter][loBound] = vec[counter][hiSwap];
vec[counter][hiSwap] = pivot[counter];
}

if (debug)
if (!confirm(loBound + " < " + (hiSwap-1)))
return;
// Recursively call function... the beauty of quicksort

// 2 or more items in first section 
if (loBound < hiSwap - 1)
QuicksortHelp(vec, k, loBound, hiSwap - 1);

if (debug)
if (!confirm((hiSwap+1) + " < " + hiBound))
return;
// 2 or more items in second section
if (hiSwap + 1 < hiBound)
QuicksortHelp(vec, k, hiSwap + 1, hiBound);
}

function swap(arr,p1,p2){
for (k=0; k temp = arr[k][p1];
arr[k][p1] = arr[k][p2];
arr[k][p2] = temp;
}
}

———————————————————

I also added the following code to sort blank entries last. You just need to run this before you call quicksort.

for (i=0; i < vec[k].length; i++){
if (vec[k][i].length <= 0){
vec[k][i] = "" + String.fromCharCode(127);
}
}

And run this after you call quicksort.

for (i=0; i < vec[k].length; i++){
if (vec[k][i] == ("" + String.fromCharCode(127))){
vec[k][i] = "";
}
}

Leave a Reply

Your email address will not be published.

*

*