Skip to content

Commit d4af68b

Browse files
committedAug 15, 2018
choose pivot from median of three elements for quicksort
1 parent c2f7e49 commit d4af68b

File tree

2 files changed

+17
-9
lines changed

2 files changed

+17
-9
lines changed
 

‎src/algorithms/sorting/quick-sort/QuickSort.js

+13-5
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,21 @@ export default class QuickSort extends Sort {
1414
return array;
1515
}
1616

17-
// Init left and right arrays.
17+
// Init left, center, and right arrays.
1818
const leftArray = [];
1919
const rightArray = [];
20-
21-
// Take the first element of array as a pivot.
22-
const pivotElement = array.shift();
23-
const centerArray = [pivotElement];
20+
const centerArray = [];
21+
22+
// Take the median element of first, mid, and last elements.
23+
let pivotElement = array[0];
24+
const mid = Math.floor(array.length / 2);
25+
if ((array[mid] < array[array.length - 1] && array[mid] > array[0])
26+
|| (array[mid] > array[array.length - 1] && array[mid] < array[0])) {
27+
pivotElement = array[mid];
28+
} else if ((array[array.length - 1] < array[mid] && array[array.length - 1] > array[0])
29+
|| (array[array.length - 1] > array[mid] && array[array.length - 1] < array[0])) {
30+
pivotElement = array[array.length - 1];
31+
}
2432

2533
// Split all array elements between left, center and right arrays.
2634
while (array.length) {

‎src/algorithms/sorting/quick-sort/__test__/QuickSort.test.js

+4-4
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,10 @@ import {
88
} from '../../SortTester';
99

1010
// Complexity constants.
11-
const SORTED_ARRAY_VISITING_COUNT = 190;
12-
const NOT_SORTED_ARRAY_VISITING_COUNT = 62;
13-
const REVERSE_SORTED_ARRAY_VISITING_COUNT = 190;
14-
const EQUAL_ARRAY_VISITING_COUNT = 19;
11+
const SORTED_ARRAY_VISITING_COUNT = 66;
12+
const NOT_SORTED_ARRAY_VISITING_COUNT = 83;
13+
const REVERSE_SORTED_ARRAY_VISITING_COUNT = 66;
14+
const EQUAL_ARRAY_VISITING_COUNT = 20;
1515

1616
describe('QuickSort', () => {
1717
it('should sort array', () => {

0 commit comments

Comments
 (0)
Please sign in to comment.