I'm trying to write a quicksort function in JavaScript. My code is below:
function test_quicksort(){
var arr = [0, 9, 8, 7, 6, 5, 4, 3, 2, 1];
arr = quicksort_by_percent_filled(arr);
Logger.log(arr);
}
function quicksort_setup(arr){
var high = arr.size - 1;
arr = quicksort_by_percent_filled(arr, 0, high);
return arr
}
function quicksort_by_percent_filled(arr, low, high){
if (low < high){
var pi = partition(arr, low, high);
quicksort_by_percent_filled(arr, low, pi - 1);
quicksort_by_percent_filled(arr, pi + 1, high);
}
return arr;
}
function partition(arr, low, high){
var pivot = arr[high];
var smaller_boundary = low - 1;
var curr_elem = low;
for (; curr_elem <= high; curr_elem++){
if (ar[curr_elem] < pivot){
smaller_boundary++;
swap(arr, curr_elem, smaller_boundary);
}
}
swap(arr, high, smaller_boundary + 1);
return smaller_boundary + 1;
}
function swap(arr, a, b){
var temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
Logger.log(arr);
}
Assuming Logger.log(arr) is a function that prints out the contents of the array, it should print out the array properly sorted. However, whenever I run test_quicksort, the [0, 9, 8, 7, 6, 5, 4, 3, 2, 1] is printed out instead. It seems to me that I am somehow unable to edit the array arr when it is passed as an argument. How can I work around this issue?
arrin any wayswapdid, but since the code isn't in the question... :-|