I have scoured the internet for all the various versions of quicksort implementation to translate into JavaScript and many of them do not successfully port.
I haven't been able to figure out if this is due to me not knowing a nuance about Java or C++, or the examples that people posted are broken.
I am not optimizing for performance, but how readable and logical it is to me.
I have arrived at this implementation, but I noticed that it does not work.
Outputs are random (likely due to the Math.random()), but as I follow the algo, I get frustrated with this following test case.
Outputs range from 999, 3, 100, 2, and 1000. I cannot follow the logic and would really appreciate someone explaining what's happening to give such erratic results.
function swap(array, idxA, idxB) {
var temp = array[idxA]
array[idxA] = array[idxB]
array[idxB] = temp
}
function partitionStart(arr, left, right, pivotIdx) {
var storeIdx = left, pivotVal = arr[pivotIdx];
swap(arr, pivotIdx, right)
for (var i = left; i <right; i++) {
if (arr[i] < pivotVal) {
swap(arr, storeIdx, i)
storeIdx++
}
}
swap(arr, pivotIdx, right);
return storeIdx;
}
function quickSelectLoop(arr, k) {
var pivotIndex, pivotNewIdx, pivotDist,
left = 0, right = arr.length-1
while(true) {
pivotIndex = Math.floor(Math.random()*arr.length)
pivotNewIdx = partitionStart(arr, left, right, pivotIndex)
pivotDist = pivotNewIdx - left
if (pivotDist === k) {
return arr[pivotNewIdx-1]
} else if (k < pivotDist) {
right = pivotNewIdx -1
} else {
k -= pivotDist+1
left = pivotNewIdx + 1
}
}
}
var test2 = [1000,999,1,2,3,100,105]
console.log(quickSelectLoop(test2, 4))
expected output from quickSelect(test2, 4) => 100 since 100 is the 4th smallest element in the collection
swap()implementation that you don't show just swaps the values between two array indices?