Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

choose pivot from median of three elements for quicksort #171

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
choose pivot from median of three elements for quicksort
larskotthoff committed Aug 15, 2018
commit d4af68bd865cffa3a3c41305f1a165bcaf3c9b25
18 changes: 13 additions & 5 deletions src/algorithms/sorting/quick-sort/QuickSort.js
Original file line number Diff line number Diff line change
@@ -14,13 +14,21 @@ export default class QuickSort extends Sort {
return array;
}

// Init left and right arrays.
// Init left, center, and right arrays.
const leftArray = [];
const rightArray = [];

// Take the first element of array as a pivot.
const pivotElement = array.shift();
const centerArray = [pivotElement];
const centerArray = [];

// Take the median element of first, mid, and last elements.
let pivotElement = array[0];
const mid = Math.floor(array.length / 2);
if ((array[mid] < array[array.length - 1] && array[mid] > array[0])
|| (array[mid] > array[array.length - 1] && array[mid] < array[0])) {
pivotElement = array[mid];
} else if ((array[array.length - 1] < array[mid] && array[array.length - 1] > array[0])
|| (array[array.length - 1] > array[mid] && array[array.length - 1] < array[0])) {
pivotElement = array[array.length - 1];
}

// Split all array elements between left, center and right arrays.
while (array.length) {
8 changes: 4 additions & 4 deletions src/algorithms/sorting/quick-sort/__test__/QuickSort.test.js
Original file line number Diff line number Diff line change
@@ -8,10 +8,10 @@ import {
} from '../../SortTester';

// Complexity constants.
const SORTED_ARRAY_VISITING_COUNT = 190;
const NOT_SORTED_ARRAY_VISITING_COUNT = 62;
const REVERSE_SORTED_ARRAY_VISITING_COUNT = 190;
const EQUAL_ARRAY_VISITING_COUNT = 19;
const SORTED_ARRAY_VISITING_COUNT = 66;
const NOT_SORTED_ARRAY_VISITING_COUNT = 83;
const REVERSE_SORTED_ARRAY_VISITING_COUNT = 66;
const EQUAL_ARRAY_VISITING_COUNT = 20;

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