-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Solution #2483
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
base: master
Are you sure you want to change the base?
Solution #2483
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,8 +4,21 @@ | |
| * Implement method Sort | ||
| */ | ||
| function applyCustomSort() { | ||
| [].__proto__.sort2 = function(compareFunction) { | ||
| // write code here | ||
| [].__proto__.sort2 = function ( | ||
| compareFunction = (a, b) => String(a) > String(b), | ||
| ) { | ||
| for (let i = 0; i < this.length - 1; i++) { | ||
| for (let j = 0; j < this.length - 1; j++) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This bubble sort implementation can be slightly optimized. After each full pass of the outer loop, the largest element for that pass is moved to its correct sorted position at the end of the unsorted portion of the array. Therefore, the inner loop doesn't need to check the elements that are already sorted. You can adjust the inner loop's condition to |
||
| if (compareFunction(this[j], this[j + 1]) > 0) { | ||
| const temp = this[j]; | ||
|
|
||
| this[j] = this[j + 1]; | ||
| this[j + 1] = temp; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return this; | ||
| }; | ||
| } | ||
|
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The default
compareFunctionis not correctly implemented. It should return a number (negative, 0, or positive) to be compliant with theArray.prototype.sortspecification, but it returns a boolean. For example, sorting[10, 1]will not work as expected because'10' > '1'evaluates tofalse. A correct implementation could useString.prototype.localeCompareor explicit checks to return-1,0, or1.