Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 41a07ec

Browse files
improve insertion sort
1 parent c47e322 commit 41a07ec

File tree

3 files changed

+7
-6
lines changed

3 files changed

+7
-6
lines changed

‎book/chapters/selection-sort.adoc‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
The selection sort is a simple sorting algorithm. As its name indicates, it chooses the lowest element from the list and move it where it should be.
44

5-
TIP: selection sort is a in-place sorting algorithms, it should be used when auxiliary memory is limited.
5+
TIP: Selection sort is a in-place sorting algorithms, it should be used when auxiliary memory is limited.
66

77
.Selection sort algorithm
88
. Start with the element in position 0.
@@ -38,7 +38,7 @@ It uses JavaScript ES6 destructing arrays.
3838
3939
A variable can be assign to its values using the destructing syntax.
4040
41-
[source, js]
41+
[source, javascript]
4242
----
4343
let a, b;
4444
@@ -51,7 +51,7 @@ console.log(b); //️↪️ 2
5151
5252
Two variables values can be swapped in one destructuring expression.
5353
54-
[source, js]
54+
[source, javascript]
5555
----
5656
[a, b] = [b, a];
5757
console.log(a); //↪️ 2

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,10 @@ const { swap } = require('./sorting-common');
1111
function insertionSort(collection) {
1212
const array = Array.from(collection);
1313

14-
for (let outer = 0; outer < array.length; outer+=1) {
14+
for (let outer = 1; outer < array.length; outer++) {
1515
const insert = array[outer];
1616

17-
for (let inner = outer - 1; inner>=0&&array[inner] > insert; inner-=1) {
17+
for (let inner = outer - 1; array[inner] > insert; inner--) {
1818
swap(array, inner + 1, inner);
1919
}
2020
}

‎src/algorithms/sorting/sorting-common.js‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@
77
* @param {integer} to index of the 2nd element
88
*/
99
function swap(array, from, to) {
10-
[array[from], array[to]] = [array[to], array[from]]; // ES6 array destructing
10+
// ES6 array destructing
11+
[array[from], array[to]] = [array[to], array[from]];
1112
}
1213
// end::swap[]
1314

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /