-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Develop #2451
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?
Develop #2451
Changes from all commits
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 | ||
| const compareByDefault = (a, b) => (String(a) > String(b) ? 1 : -1); | ||
|
|
||
| [].__proto__.sort2 = function (callback = compareByDefault) { | ||
| for (let j = 0; j < this.length; 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. Your bubble sort implementation is correct. For a future improvement, consider that after each pass of this outer loop, the largest remaining element moves to its correct sorted position. You can optimize the algorithm by reducing the range of the inner loop in subsequent passes (e.g., |
||
| for (let i = 0; i < this.length - 1; i++) { | ||
| if (callback(this[i], this[i + 1]) > 0) { | ||
| const temp = this[i]; | ||
|
|
||
| this[i] = this[i + 1]; | ||
| this[i + 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.
This default comparison function works for sorting, but a standard compare function should return
0for equal values. Here, ifString(a)is equal toString(b), the function returns-1. Consider adding an explicit check for equality.