Skip to content
15 changes: 15 additions & 0 deletions src/arrayMethodSort.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,22 @@
function applyCustomSort() {
[].__proto__.sort2 = function(compareFunction) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The native Array.prototype.sort method has a default behavior for when no compareFunction is provided (it converts elements to strings and compares them). Your implementation will throw an error if called without an argument. Consider adding a default comparator if compareFunction is undefined.

// write code here
for (let i = this.length; i > 1; i--) {
for(let j = 0; j < i; j++) {
if (compareFunction(this[j], this[i]) < 0) {
swap(this, i, 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 sorting algorithm has a couple of logical issues that prevent it from working correctly:

  1. The outer loop starts with i = this.length, which will cause an error because this[this.length] is undefined. Array indices only go up to length - 1.
  2. The comparison logic is flawed. You are comparing each element this[j] against a single element this[i]. A common sorting algorithm like bubble sort works by comparing adjacent elements (e.g., this[j] and this[j + 1]) and swapping them if they are in the wrong order.


return this;
};
}

function swap(arr, firstElementIndex, secondElementIndex) {
const tempPlaceHolder = arr[firstElementIndex];
arr[firstElementIndex] = arr[secondElementIndex];
arr[secondElementIndex] = tempPlaceHolder;
}

module.exports = applyCustomSort;
Loading