mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-11-14 06:52:59 +08:00
optimized for loop & corrected comments (#617)
The existing insertion sort implementation began by iterating from 0 until the end of the array, but it is only necessary to iterate from 1 until the end of the array, since at the 0th index, there is nothing to compare to the left of the element. In order to complete this change, I also had to update the tests to reflect the fact that the algorithm visits each index 1 less time. Finally, I corrected the grammar/wording of the comments. Co-authored-by: Oleksii Trekhleb <trehleb@gmail.com>
This commit is contained in:
parent
81240342c2
commit
cf61af59c5
@ -5,14 +5,14 @@ export default class InsertionSort extends Sort {
|
|||||||
const array = [...originalArray];
|
const array = [...originalArray];
|
||||||
|
|
||||||
// Go through all array elements...
|
// Go through all array elements...
|
||||||
for (let i = 0; i < array.length; i += 1) {
|
for (let i = 1; i < array.length; i += 1) {
|
||||||
let currentIndex = i;
|
let currentIndex = i;
|
||||||
|
|
||||||
// Call visiting callback.
|
// Call visiting callback.
|
||||||
this.callbacks.visitingCallback(array[i]);
|
this.callbacks.visitingCallback(array[i]);
|
||||||
|
|
||||||
// Go and check if previous elements and greater then current one.
|
// Check if previous element is greater than current element.
|
||||||
// If this is the case then swap that elements.
|
// If so, swap the two elements.
|
||||||
while (
|
while (
|
||||||
array[currentIndex - 1] !== undefined
|
array[currentIndex - 1] !== undefined
|
||||||
&& this.comparator.lessThan(array[currentIndex], array[currentIndex - 1])
|
&& this.comparator.lessThan(array[currentIndex], array[currentIndex - 1])
|
||||||
|
@ -8,10 +8,10 @@ import {
|
|||||||
} from '../../SortTester';
|
} from '../../SortTester';
|
||||||
|
|
||||||
// Complexity constants.
|
// Complexity constants.
|
||||||
const SORTED_ARRAY_VISITING_COUNT = 20;
|
const SORTED_ARRAY_VISITING_COUNT = 19;
|
||||||
const NOT_SORTED_ARRAY_VISITING_COUNT = 101;
|
const NOT_SORTED_ARRAY_VISITING_COUNT = 100;
|
||||||
const REVERSE_SORTED_ARRAY_VISITING_COUNT = 210;
|
const REVERSE_SORTED_ARRAY_VISITING_COUNT = 209;
|
||||||
const EQUAL_ARRAY_VISITING_COUNT = 20;
|
const EQUAL_ARRAY_VISITING_COUNT = 19;
|
||||||
|
|
||||||
describe('InsertionSort', () => {
|
describe('InsertionSort', () => {
|
||||||
it('should sort array', () => {
|
it('should sort array', () => {
|
||||||
|
Loading…
Reference in New Issue
Block a user