Skip to content
Open

Develop #2451

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
17 changes: 15 additions & 2 deletions src/arrayMethodSort.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);

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 0 for equal values. Here, if String(a) is equal to String(b), the function returns -1. Consider adding an explicit check for equality.


[].__proto__.sort2 = function (callback = compareByDefault) {
for (let j = 0; j < this.length; j++) {

Choose a reason for hiding this comment

The 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., i < this.length - 1 - j).

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;
};
}

Expand Down