Skip to content

Commit cf61af5

Browse files
optimized for loop & corrected comments (trekhleb#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>
1 parent 8124034 commit cf61af5

File tree

2 files changed

+7
-7
lines changed

2 files changed

+7
-7
lines changed

src/algorithms/sorting/insertion-sort/InsertionSort.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,14 @@ export default class InsertionSort extends Sort {
55
const array = [...originalArray];
66

77
// Go through all array elements...
8-
for (let i = 0; i < array.length; i += 1) {
8+
for (let i = 1; i < array.length; i += 1) {
99
let currentIndex = i;
1010

1111
// Call visiting callback.
1212
this.callbacks.visitingCallback(array[i]);
1313

14-
// Go and check if previous elements and greater then current one.
15-
// If this is the case then swap that elements.
14+
// Check if previous element is greater than current element.
15+
// If so, swap the two elements.
1616
while (
1717
array[currentIndex - 1] !== undefined
1818
&& this.comparator.lessThan(array[currentIndex], array[currentIndex - 1])

src/algorithms/sorting/insertion-sort/__test__/InsertionSort.test.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,10 @@ import {
88
} from '../../SortTester';
99

1010
// Complexity constants.
11-
const SORTED_ARRAY_VISITING_COUNT = 20;
12-
const NOT_SORTED_ARRAY_VISITING_COUNT = 101;
13-
const REVERSE_SORTED_ARRAY_VISITING_COUNT = 210;
14-
const EQUAL_ARRAY_VISITING_COUNT = 20;
11+
const SORTED_ARRAY_VISITING_COUNT = 19;
12+
const NOT_SORTED_ARRAY_VISITING_COUNT = 100;
13+
const REVERSE_SORTED_ARRAY_VISITING_COUNT = 209;
14+
const EQUAL_ARRAY_VISITING_COUNT = 19;
1515

1616
describe('InsertionSort', () => {
1717
it('should sort array', () => {

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy