|
| 1 | +/** |
| 2 | + * |
| 3 | + sort() method returns a sorted array from it's calling array. |
| 4 | +
|
| 5 | + sort() takes at most 1 parameter: |
| 6 | +
|
| 7 | + - comparator, compreing function which specifies how to compare elements. If |
| 8 | + not provided, a default comparator which compares 2 elements by their |
| 9 | + values in ascending order. |
| 10 | +
|
| 11 | + The comparator function takes 2 parameters, value for comparing 2 elements. |
| 12 | + |
| 13 | + Test Example 1: |
| 14 | + let numberArray = [4, 8, 9, 1, 2, 3, 5, 5]; |
| 15 | + console.log(numberArray.sort()); |
| 16 | + Return: |
| 17 | + [ 1, 2, 3, 4, 5, 5, 8, 9 ] |
| 18 | +
|
| 19 | + Test Example 2: |
| 20 | + let stringArray = ['a', 'b', 'h', 'y', 'q', 'j', 't', 'h']; |
| 21 | + console.log(stringArray.sort()); |
| 22 | + Return: |
| 23 | + [ 'a', 'b', 'h', 'h', 'j', 'q', 't', 'y' ] |
| 24 | +
|
| 25 | + Test Example 3: |
| 26 | + let numberElements = [{ a:5 }, { a:2 }, { a:9 }, { a:7 }, { a:4 }, { a:8 }]; |
| 27 | + console.log(numberElements.sort((a, b) => { return a.a - b.a; } )) |
| 28 | + Return: |
| 29 | + [ { a: 2 }, { a: 4 }, { a: 5 }, { a: 7 }, { a: 8 }, { a: 9 } ] |
| 30 | +
|
| 31 | + Test Example 4: |
| 32 | + let stringElements = [{ a:'5' }, { a:'2' }, { a:'9' }, { a:'7' }, { a:'4' }, { a:'8' }]; |
| 33 | + console.log(stringElements.sort((a, b) => { return a.a - b.a; } )) |
| 34 | + Return: |
| 35 | + [ { a: '2' }, { a: '4' }, { a: '5' }, { a: '7' }, { a: '8' }, { a: '9' } ] |
| 36 | +*/ |
| 37 | + |
| 38 | +Array.prototype.sort = function sort(comparator) { |
| 39 | + if (comparator == null) { |
| 40 | + comparator = function(a, b) { |
| 41 | + if (a < b) { |
| 42 | + return -1; |
| 43 | + } |
| 44 | + |
| 45 | + if (a > b) { |
| 46 | + return 1; |
| 47 | + } |
| 48 | + |
| 49 | + return 0; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + let sortedArray = [...this]; |
| 54 | + |
| 55 | + function recursiveSort(start, end) { |
| 56 | + if (end - start < 1) { |
| 57 | + return; |
| 58 | + } |
| 59 | + |
| 60 | + const pivot = sortedArray[end]; |
| 61 | + let split = start; |
| 62 | + |
| 63 | + for (let i = start; i < end; i++) { |
| 64 | + const compareVaule = comparator(sortedArray[i], pivot); |
| 65 | + |
| 66 | + if (compareVaule < 0) { |
| 67 | + if (split != i) { |
| 68 | + const temp = sortedArray[split]; |
| 69 | + sortedArray[split] = sortedArray[i]; |
| 70 | + sortedArray[i] = temp; |
| 71 | + } |
| 72 | + |
| 73 | + split++; |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + sortedArray[end] = sortedArray[split]; |
| 78 | + sortedArray[split] = pivot; |
| 79 | + |
| 80 | + recursiveSort(start, split - 1); |
| 81 | + recursiveSort(split + 1, end); |
| 82 | + } |
| 83 | + |
| 84 | + recursiveSort(0, this.length - 1); |
| 85 | + |
| 86 | + return sortedArray; |
| 87 | +}; |
0 commit comments