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

switch shift to pop #300

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
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
4 changes: 2 additions & 2 deletions src/algorithms/sorting/quick-sort/QuickSort.js
Original file line number Diff line number Diff line change
@@ -19,12 +19,12 @@ export default class QuickSort extends Sort {
const rightArray = [];

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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shift and pop are used for different purposes. shift removes element from the front of the array and pop removes from the end. hence pop cannot used to get the first element in the array.

Copy link
Contributor Author

@henrycjchen henrycjchen May 4, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in this sutiation, it can work well no matter the element is taken from the front of the array or the end

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@chandrunaik and @mrbeannnnn , in this case pop is better than shift because pop is O(1) (constant operation) where as shift() is O(n) .

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

quick-sort should work well not metter the element is get from the top or from the end.
while in JS, pop is faster than shift, as talentedandrew said above.
so I think pop is better here.

const centerArray = [pivotElement];

// Split all array elements between left, center and right arrays.
while (array.length) {
const currentElement = array.shift();
const currentElement = array.pop();

// Call visiting callback.
this.callbacks.visitingCallback(currentElement);