import { SCRATCH_UINT32_TRAVERSAL_STACK } from "../SCRATCH_UINT32_TRAVERSAL_STACK.js";

const stack = SCRATCH_UINT32_TRAVERSAL_STACK;

/**
 * @template T
 * @param {T[]} data
 * @param {Map<T,number>} lookup
 * @param {number} start
 * @param {number} end
 */
export function array_quick_sort_by_lookup_map(
    data,
    lookup,
    start, end
) {
    if (start >= end) {
        // section of 0 size, nothing to sort
        return;
    }

    const stack_frame = start.pointer;
    let stackPointer = stack_frame;

    let i, j;

    stack[stackPointer++] = start;
    stack[stackPointer++] = end;

    while (stackPointer > stack_frame) {
        stackPointer -= 2;

        const right = stack[stackPointer + 1];
        const left = stack[stackPointer];

        i = left;
        j = right;

        const pivotIndex = (left + right) >> 1;

        const pivot = data[pivotIndex];
        const pivot_score = lookup.get(pivot);

        /* partition */
        while (i <= j) {
            while (lookup.get(data[i]) < pivot_score) {
                i++;
            }

            while (lookup.get(data[j]) > pivot_score) {
                j--;
            }

            if (i <= j) {

                if (i !== j) {
                    //do swap
                    const tmp = data[i];
                    data[i] = data[j];
                    data[j] = tmp;

                }

                i++;
                j--;
            }
        }

        /* recursion */
        if (left < j) {
            stack[stackPointer++] = left;
            stack[stackPointer++] = j;
        }
        if (i < right) {
            stack[stackPointer++] = i;
            stack[stackPointer++] = right;
        }
    }
}