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
31 changes: 29 additions & 2 deletions src/arrayMethodSort.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,35 @@
* Implement method Sort
*/
function applyCustomSort() {
[].__proto__.sort2 = function(compareFunction) {
// write code here
[].__proto__.sort2 = function (compareFunction) {
const arr = this;

const compare =
compareFunction ||
function (a, b) {
if (String(a) > String(b)) {
return 1;
}

if (String(a) < String(b)) {
return -1;
}

return 0;
};

for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length - 1; j++) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This implementation of bubble sort is functional, but it performs unnecessary comparisons in later iterations. After each pass of the outer loop (controlled by i), the largest unsorted element 'bubbles up' to its final position at the end of the array. You can optimize this by reducing the upper bound of this inner loop with each outer loop pass. Consider adjusting the loop's condition to j < arr.length - 1 - i to avoid comparing elements that are already in their correct sorted position.

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

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

return arr;
};
}

Expand Down
Loading