@@ -5,7 +5,58 @@ The selection sort as it names indicates choose the lowest element from the list
5
5
TIP: selection sort is a in-place sorting algorithms, it should be used when auxiliary memory is limited.
6
6
7
7
.Selection sort algorithm
8
- . Go throught the array a find the smallest element, swap it with index 0
9
- . Go to the next position and find the smallest from there on, swap the 2nd smallest element with the index 1
10
- . Repeat until the end of the array .
8
+ . Start with the element in position 0.
9
+ . Find minimum element in the rest of array. If a new minimun is found swap them.
10
+ . Repeat with the element in postion 1 and so until the last one .
11
11
12
+ image:https://camo.githubusercontent.com/adfa2cdcc3825092dc405aadd87453571d6e0dc4/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f392f39342f53656c656374696f6e2d536f72742d416e696d6174696f6e2e676966[]
13
+
14
+ == Selection sort implementation
15
+ For implementing the selection sort we need 2 indexes.
16
+
17
+ .Selection sort
18
+ [source, javascript]
19
+ ----
20
+ include::{codedir}/algorithms/selection-sort.js[tag=sort, indent=0]
21
+ ----
22
+
23
+ One index is for the position in question (selection/outer) and another one for finding the minimun in the rest of the array (element/inner).
24
+
25
+ The swap function is implemented as follows.
26
+
27
+ .Swap function
28
+ [source, javascript]
29
+ ----
30
+ include::{codedir}/algorithms/selection-sort.js[tag=swap, indent=0]
31
+ ----
32
+
33
+ It uses JavaScript ES6 destructing arrays.
34
+
35
+ .JavaScript Array destructuring
36
+ ****
37
+ *Assignment separate from declaration*
38
+
39
+ A variable can be assign to its values using the destructing syntax.
40
+
41
+ [source, js]
42
+ ----
43
+ let a, b;
44
+
45
+ [a, b] = [1, 2];
46
+ console.log(a); //↪️ 1
47
+ console.log(b); //️↪️ 2
48
+ ----
49
+
50
+ *Swapping variables*
51
+
52
+ Two variables values can be swapped in one destructuring expression.
53
+
54
+ [source, js]
55
+ ----
56
+ [a, b] = [b, a];
57
+ console.log(a); //↪️ 2
58
+ console.log(b); //️↪️ 1
59
+ ----
60
+
61
+ Without destructuring assignment, swapping two values requires a temporary variable.
62
+ ****
0 commit comments