Code style fixes for negative Counting Sort testing.

This commit is contained in:
Oleksii Trekhleb 2018-07-22 18:23:39 +03:00
parent 3be02b5519
commit 76c172b20b
2 changed files with 19 additions and 8 deletions

View File

@ -3,21 +3,26 @@ import Sort from '../Sort';
export default class CountingSort extends Sort {
/**
* @param {number[]} originalArray
* @param {number} [smallestElement]
* @param {number} [biggestElement]
*/
sort(originalArray, smallestElement = 0, biggestElement = 0) {
// Detect biggest element in array in order to build number bucket array later.
let detectedSmallestElement = smallestElement;
let detectedBiggestElement = biggestElement;
if (!detectedBiggestElement) {
sort(originalArray, smallestElement = undefined, biggestElement = undefined) {
// Init biggest and smallest elements in array in order to build number bucket array later.
let detectedSmallestElement = smallestElement || 0;
let detectedBiggestElement = biggestElement || 0;
if (smallestElement === undefined || biggestElement === undefined) {
originalArray.forEach((element) => {
// Visit element.
this.callbacks.visitingCallback(element);
// Detect biggest element.
if (this.comparator.greaterThan(element, detectedBiggestElement)) {
detectedBiggestElement = element;
}
if (this.comparator.greaterThan(detectedSmallestElement, element)) {
// Detect smallest element.
if (this.comparator.lessThan(element, detectedSmallestElement)) {
detectedSmallestElement = element;
}
});
@ -26,6 +31,7 @@ export default class CountingSort extends Sort {
// Init buckets array.
// This array will hold frequency of each number from originalArray.
const buckets = Array(detectedBiggestElement - detectedSmallestElement + 1).fill(0);
originalArray.forEach((element) => {
// Visit element.
this.callbacks.visitingCallback(element);

View File

@ -22,7 +22,7 @@ describe('CountingSort', () => {
SortTester.testNegativeNumbersSort(CountingSort);
});
it('should allow to use specify maximum integer value in array to make sorting faster', () => {
it('should allow to use specify max/min integer value in array to make sorting faster', () => {
const visitingCallback = jest.fn();
const sorter = new CountingSort({ visitingCallback });
@ -31,7 +31,12 @@ describe('CountingSort', () => {
return element > accumulator ? element : accumulator;
}, 0);
const sortedArray = sorter.sort(notSortedArr, 0, biggestElement);
// Detect smallest number in array in prior.
const smallestElement = notSortedArr.reduce((accumulator, element) => {
return element < accumulator ? element : accumulator;
}, 0);
const sortedArray = sorter.sort(notSortedArr, smallestElement, biggestElement);
expect(sortedArray).toEqual(sortedArr);
// Normally visitingCallback is being called 60 times but in this case