From 6c61bb02f01c58fcb1267b54107ddd033bbb6905 Mon Sep 17 00:00:00 2001 From: wiliammunchen Date: Tue, 24 Mar 2026 01:13:35 -0300 Subject: [PATCH 1/2] feat: implement custom sort method --- src/arrayMethodSort.js | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/src/arrayMethodSort.js b/src/arrayMethodSort.js index 32363d0d..ad5c344e 100644 --- a/src/arrayMethodSort.js +++ b/src/arrayMethodSort.js @@ -4,8 +4,36 @@ * Implement method Sort */ function applyCustomSort() { - [].__proto__.sort2 = function(compareFunction) { - // write code here + [].__proto__.sort2 = function (compareFunction) { + const compare = + compareFunction || + ((firstElement, secondElement) => { + const firstString = String(firstElement); + const secondString = String(secondElement); + + if (firstString > secondString) { + return 1; + } + + if (firstString < secondString) { + return -1; + } + + return 0; + }); + + for (let i = 0; i < this.length - 1; i++) { + for (let j = 0; j < this.length - 1 - i; j++) { + if (compare(this[j], this[j + 1]) > 0) { + const currentValue = this[j]; + + this[j] = this[j + 1]; + this[j + 1] = currentValue; + } + } + } + + return this; }; } From 988be0a98aa2312e3aeea10c51a4598ce964bd3d Mon Sep 17 00:00:00 2001 From: wiliammunchen Date: Tue, 24 Mar 2026 01:16:17 -0300 Subject: [PATCH 2/2] feat: update custom sort2 method --- src/arrayMethodSort.js | 39 ++++++++++++++++++++++++++++++++------- 1 file changed, 32 insertions(+), 7 deletions(-) diff --git a/src/arrayMethodSort.js b/src/arrayMethodSort.js index ad5c344e..c5836bf4 100644 --- a/src/arrayMethodSort.js +++ b/src/arrayMethodSort.js @@ -22,16 +22,41 @@ function applyCustomSort() { return 0; }); - for (let i = 0; i < this.length - 1; i++) { - for (let j = 0; j < this.length - 1 - i; j++) { - if (compare(this[j], this[j + 1]) > 0) { - const currentValue = this[j]; + const swap = (leftIndex, rightIndex) => { + const temp = this[leftIndex]; - this[j] = this[j + 1]; - this[j + 1] = currentValue; + this[leftIndex] = this[rightIndex]; + this[rightIndex] = temp; + }; + + const partition = (start, end) => { + const pivot = this[end]; + let smallerElementIndex = start; + + for (let currentIndex = start; currentIndex < end; currentIndex++) { + if (compare(this[currentIndex], pivot) <= 0) { + swap(smallerElementIndex, currentIndex); + smallerElementIndex++; } } - } + + swap(smallerElementIndex, end); + + return smallerElementIndex; + }; + + const quickSort = (start, end) => { + if (start >= end) { + return; + } + + const pivotIndex = partition(start, end); + + quickSort(start, pivotIndex - 1); + quickSort(pivotIndex + 1, end); + }; + + quickSort(0, this.length - 1); return this; };