Skip to content
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
34 changes: 32 additions & 2 deletions src/arrayMethodSort.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,38 @@
* Implement method Sort
*/
function applyCustomSort() {
[].__proto__.sort2 = function(compareFunction) {
// write code here
[].__proto__.sort2 = function (compareFunction) {
let callback = compareFunction;

if (!compareFunction) {
callback = (item1, item2) => {
const strItem1 = String(item1);
const strItem2 = String(item2);

if (strItem1 > strItem2) {
return 1;
}

if (strItem1 < strItem2) {
return -1;
}

return 0;
};
}

for (let i = 0; i < this.length; i++) {
for (let j = 0; j < this.length - 1; j++) {

Choose a reason for hiding this comment

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

This bubble sort implementation is correct, but it can be optimized. With each iteration of the outer loop, the largest element is moved to the end of the unsorted portion of the array. You can avoid unnecessary comparisons by reducing the range of this inner loop in each iteration. For example, you could change the condition to j < this.length - 1 - i.

if (callback(this[j], this[j + 1]) > 0) {
const temp = this[j];

this[j] = this[j + 1];
this[j + 1] = temp;
}
}
}

return this;
};
}

Expand Down