MCPcopy Create free account
hub / github.com/betomoedano/JavaScript-Coding-Interview-Questions / quickSortHelper

Function quickSortHelper

sorting/quick-sort.js:10–37  ·  view source on GitHub ↗
(array, startIdx, endIdx)

Source from the content-addressed store, hash-verified

8}
9
10function quickSortHelper(array, startIdx, endIdx) {
11 if (startIdx >= endIdx) return;
12 let pivotIdx = startIdx;
13 let leftIdx = startIdx + 1;
14 let rightIdx = endIdx;
15
16 while (rightIdx >= leftIdx) {
17 const pivotNumber = array[pivotIdx];
18 const leftNumber = array[leftIdx];
19 const rightNumber = array[rightIdx];
20
21 if (leftNumber > pivotNumber && rightNumber < pivotNumber) {
22 swap(leftIdx, rightIdx, array);
23 }
24 if (leftNumber <= pivotNumber) leftIdx++;
25 if (rightNumber >= pivotNumber) rightIdx--;
26 }
27 swap(pivotIdx, rightIdx, array);
28 const leftSubarrayIsSmaller =
29 rightIdx - 1 - startIdx < endIdx - (rightIdx + 1);
30 if (leftSubarrayIsSmaller) {
31 quickSortHelper(array, startIdx, rightIdx - 1);
32 quickSortHelper(array, rightIdx + 1, endIdx);
33 } else {
34 quickSortHelper(array, rightIdx + 1, endIdx);
35 quickSortHelper(array, startIdx, rightIdx - 1);
36 }
37}
38
39function swap(i, j, array) {
40 const temp = array[j];

Callers 1

quickSortFunction · 0.85

Calls 1

swapFunction · 0.70

Tested by

no test coverage detected