import { assert } from "../../../../core/assert.js";

/**
 *
 * @param {number[]|ArrayLike<number>|Uint32Array|Int32Array} pSortBuffer
 * @param {number} iLeft
 * @param {number} iRight
 * @param {number} uSeed
 * @returns {void}
 */
export function QuickSort(pSortBuffer, iLeft, iRight, uSeed) {
    let iL, iR, n, index, iMid, iTmp;

    // Random
    let t = uSeed & 31;
    t = (uSeed << t) | (uSeed >> (32 - t));
    uSeed = uSeed + t + 3;
    uSeed = uSeed >>> 0; // make unsigned
    // Random end

    iL = iLeft;
    iR = iRight;
    n = (iR - iL) + 1;

    assert.greaterThanOrEqual(n , 0);

    index = (uSeed % n);

    iMid = pSortBuffer[index + iL];


    do {
        while (pSortBuffer[iL] < iMid)
            ++iL;
        while (pSortBuffer[iR] > iMid)
            --iR;

        if (iL <= iR) {

            iTmp = pSortBuffer[iL];
            pSortBuffer[iL] = pSortBuffer[iR];
            pSortBuffer[iR] = iTmp;

            ++iL;
            --iR;
        }
    }
    while (iL <= iR);

    if (iLeft < iR)
        QuickSort(pSortBuffer, iLeft, iR, uSeed);
    if (iL < iRight)
        QuickSort(pSortBuffer, iL, iRight, uSeed);
}
