From dd91e540d5fd51c36fc720b854a9d3d6dad18940 Mon Sep 17 00:00:00 2001 From: vladimir-cucu Date: Mon, 16 Oct 2023 22:51:52 +0300 Subject: [PATCH] fix: Fix QuickSort --- sorts/quick_sort.ts | 44 ++++++++++++++++++++++++++------------------ 1 file changed, 26 insertions(+), 18 deletions(-) diff --git a/sorts/quick_sort.ts b/sorts/quick_sort.ts index c0fd192e..90d03266 100644 --- a/sorts/quick_sort.ts +++ b/sorts/quick_sort.ts @@ -10,29 +10,39 @@ export const partition = ( left: number = 0, right: number = array.length - 1 ) => { - const pivot = array[Math.floor((right + left) / 2)]; - let i = left; + const pivotIndex = choosePivot(left,right); + const pivot = array[pivotIndex]; + [array[pivotIndex], array[right]] = [array[right], array[pivotIndex]]; + let i = left - 1; let j = right; - while (i <= j) { - while (array[i] < pivot) { - i++; - } - - while (array[j] > pivot) { - j--; - } + while (i < j) { + while (array[++i] < pivot); + while (array[--j] > pivot); - if (i <= j) { + if (i < j) { [array[i], array[j]] = [array[j], array[i]]; - i++; - j--; } } + [array[right], array[i]] = [array[i], array[right]]; return i; }; +/** + * @function choosePivot + * @description Chooses a pivot element randomly within the subarray. + * @param {number} left - The left index of the subarray. + * @param {number} right - The right index of the subarray. + * @returns {number} - The index of the chosen pivot element. + */ +const choosePivot = ( + left: number, + right: number +): number => { + return Math.floor(Math.random() * (right - left + 1)) + left; +}; + /** * Quicksort implementation * @@ -56,17 +66,15 @@ export const QuickSort = ( left: number = 0, right: number = array.length - 1 ) => { - let index; - if (array.length > 1) { - index = partition(array, left, right); + const index = partition(array, left, right); if (left < index - 1) { QuickSort(array, left, index - 1); } - if (index < right) { - QuickSort(array, index, right); + if (index + 1 < right) { + QuickSort(array, index + 1, right); } }