Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: trekhleb/javascript-algorithms
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: master
Choose a base ref
...
head repository: AryanAhadinia/javascript-algorithms-1
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: issue_567
Choose a head ref
  • 3 commits
  • 1 file changed
  • 1 contributor

Commits on Dec 16, 2020

  1. Optimize swap

    AryanAhadinia committed Dec 16, 2020
    Copy the full SHA
    16d6ed8 View commit details

Commits on Dec 17, 2020

  1. Opmize iterations

    AryanAhadinia committed Dec 17, 2020
    Copy the full SHA
    71777d6 View commit details
  2. Copy the full SHA
    cce1d13 View commit details
Showing with 6 additions and 11 deletions.
  1. +6 −11 src/algorithms/sorting/insertion-sort/InsertionSort.js
17 changes: 6 additions & 11 deletions src/algorithms/sorting/insertion-sort/InsertionSort.js
Original file line number Diff line number Diff line change
@@ -7,31 +7,26 @@ export default class InsertionSort extends Sort {
// Go through all array elements...
for (let i = 0; i < array.length; i += 1) {
let currentIndex = i;
const valueAtIndex = array[i];

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

// Go and check if previous elements and greater then current one.
// If this is the case then swap that elements.
while (
array[currentIndex - 1] !== undefined
&& this.comparator.lessThan(array[currentIndex], array[currentIndex - 1])
while (currentIndex > 0
&& this.comparator.lessThan(valueAtIndex, array[currentIndex - 1])
) {
// Call visiting callback.
this.callbacks.visitingCallback(array[currentIndex - 1]);

// Swap the elements.
[
array[currentIndex - 1],
array[currentIndex],
] = [
array[currentIndex],
array[currentIndex - 1],
];
array[currentIndex] = array[currentIndex - 1];

// Shift current index left.
currentIndex -= 1;
}

array[currentIndex] = valueAtIndex;
}

return array;