Hope you don't mind, I did some edits to the quicksort! I added the ability to compare any object using a custom function.
PHP Code:
/**
* Compares two values and returns a value that represents an order.
*
* If A < B, output is negative
* If A == B, output is zero
* If A > B, output is positive
*
* @param object First element to compare
* @param object Second element to compare
*/
function default_cmp( sideA, sideB ) {
return (sideA - sideB);
}
/**
* Adaptor method for quicksort.
*
* @param array The array to be sorted.
* @param function The function that compares two elements
*/
function quicksort(array, compare_function ) {
this.cmp = ( temp.compare_function == null ? this.default_cmp : temp.compare_function );
qsort(array, 0, array.size()-1, compare_function);
}
/**
* Sorts the array with the quicksort algorithm.
*
* Average Case Time Complexity of O(n log n).
* Worst Case Time Complexity of O(n**2).
* Average Case Space Complexity of O(log n).
* n = array size
*
* @param array The array to be sorted
* @param int The position of the left side of the array
* @param int The position of the right side of the array
* @param function The function that compares two elements
*/
function qsort(temp.array, temp.left, temp.right ) {
if (temp.right > temp.left) {
temp.pivotNewIndex = qsort_partition(temp.array, temp.left, temp.right, temp.left );
qsort(temp.array, temp.left, temp.pivotNewIndex - 1 );
qsort(temp.array, temp.pivotNewIndex + 1, temp.right );
}
return temp.array;
}
/**
* In-place parition algorithm. Paritions the portion of
* the array between indexs left and right, inclusively.
*
* @param array The array to be partitioned
* @param int The left bound
* @param int The right bound
* @param int The pivot index
* @param function The function that compares two elements
*/
function qsort_partition(temp.array, temp.left, temp.right, temp.pivotIndex ) {
temp.pivotValue = temp.array[temp.pivotIndex];
temp.s = temp.array[temp.right];
temp.array[temp.right] = temp.array[temp.pivotIndex];
temp.array[temp.pivotIndex] = temp.s;
temp.storeIndex = temp.left;
for (temp.i = temp.left; temp.i < temp.right; temp.i++) {
if ( cmp( temp.array[temp.i], temp.pivotValue ) <= 0 ) {
temp.s = temp.array[temp.storeIndex];
temp.array[temp.storeIndex] = temp.array[temp.i];
temp.array[temp.i] = temp.s;
temp.storeIndex++;
}
}
temp.s = temp.array[temp.right];
temp.array[temp.right] = temp.array[temp.storeIndex];
temp.array[temp.storeIndex] = temp.s;
return temp.storeIndex;
}
This allows you to actually sort multi-dimensional array with specific indexes (or objects with values):
PHP Code:
temp.compare_function = function(a,b){
return (a[0] - b[0]);
};
quicksort( initial_list, temp.compare_function );
Or decreasing order:
PHP Code:
temp.compare_function = function(a,b){
return (b - a);
};
quicksort( initial_list, temp.compare_function );
Or whatever way you wish to sort.