Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
7944d3c
commit aedac73
Showing
1 changed file
with
38 additions
and
30 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,41 +1,49 @@ | ||
'use strict'; | ||
|
||
import { swap } from './helper.js'; | ||
|
||
/** | ||
* @param {Array} elements | ||
* @param {number} left | ||
* @param {number} right | ||
* @return {Array} | ||
*/ | ||
function partition (elements, left, right) { | ||
const pivot = elements[right]; | ||
let partitionIndex = left; | ||
export default function (elements) { | ||
qsort(0, elements.length - 1); | ||
|
||
for (let i = left; i < right; i++) { | ||
if (elements[i] < pivot) { | ||
swap(elements, i, partitionIndex++); | ||
} | ||
} | ||
return elements; | ||
|
||
swap(elements, right, partitionIndex); | ||
/** | ||
* @param {number} start | ||
* @return {number} end | ||
*/ | ||
function qsort (start, end) { | ||
if (start >= end) return; | ||
|
||
return partitionIndex; | ||
} | ||
const pivot = elements[end]; | ||
let left = start; | ||
let right = end - 1; | ||
|
||
/** | ||
* @param {Array} elements | ||
* @param {number} left | ||
* @param {number} right | ||
* @return {Array} | ||
*/ | ||
export default function quickSort (elements, left = 0, right = (elements.length - 1)) { | ||
if (elements.length > 1 && left < right) { | ||
const partitionIndex = partition(elements, left, right); | ||
while (left <= right) { | ||
while (left <= end && elements[left] < pivot) { | ||
left++; | ||
} | ||
|
||
while (right >= start && elements[right] > pivot) { | ||
right--; | ||
} | ||
|
||
quickSort(elements, left, partitionIndex - 1); | ||
quickSort(elements, partitionIndex + 1, right); | ||
if (left >= right) break; | ||
|
||
swap(left, right); | ||
left++; | ||
right--; | ||
} | ||
|
||
swap(end, left); | ||
qsort(start, left - 1); | ||
qsort(left + 1, end); | ||
} | ||
|
||
return elements; | ||
}; | ||
/** | ||
* @param {number} i | ||
* @param {number} j | ||
*/ | ||
function swap (i, j) { | ||
[elements[i], elements[j]] = [elements[j], elements[i]]; | ||
} | ||
} |