|
8 | 8 | *from the unsorted subarray is picked and moved to the sorted subarray.
|
9 | 9 | */
|
10 | 10 |
|
11 |
| -function selectionSort (items) { |
12 |
| - var length = items.length |
13 |
| - for (var i = 0; i < length - 1; i++) { |
| 11 | +const selectionSort = (list) => { |
| 12 | + if (!Array.isArray(list)) { |
| 13 | + throw new TypeError('Given input is not an array') |
| 14 | + } |
| 15 | + const items = [...list] // We don't want to modify the original array |
| 16 | + const length = items.length |
| 17 | + for (let i = 0; i < length - 1; i++) { |
| 18 | + if (typeof items[i] !== 'number') { |
| 19 | + throw new TypeError('One of the items in your array is not a number') |
| 20 | + } |
14 | 21 | // Number of passes
|
15 |
| - var min = i // min holds the current minimum number position for each pass; i holds the Initial min number |
16 |
| - for (var j = i + 1; j < length; j++) { // Note that j = i + 1 as we only need to go through unsorted array |
| 22 | + let min = i // min holds the current minimum number position for each pass; i holds the Initial min number |
| 23 | + for (let j = i + 1; j < length; j++) { // Note that j = i + 1 as we only need to go through unsorted array |
17 | 24 | if (items[j] < items[min]) { // Compare the numbers
|
18 | 25 | min = j // Change the current min number position if a smaller num is found
|
19 | 26 | }
|
20 | 27 | }
|
21 | 28 | if (min !== i) {
|
22 | 29 | // After each pass, if the current min num != initial min num, exchange the position.
|
23 | 30 | // Swap the numbers
|
24 |
| - [items[i], items[min]] = [items[min], [items[i]]] |
| 31 | + [items[i], items[min]] = [items[min], items[i]] |
25 | 32 | }
|
26 | 33 | }
|
| 34 | + return items |
27 | 35 | }
|
28 | 36 |
|
29 |
| -// Implementation of Selection Sort |
| 37 | +/* Implementation of Selection Sort |
| 38 | +
|
| 39 | +(() => { |
| 40 | + let array = [5, 6, 7, 8, 1, 2, 12, 14] |
| 41 | + // Array before Sort |
| 42 | + console.log(array) |
| 43 | + array = selectionSort(array) |
| 44 | + // Array after sort |
| 45 | + console.log(array) |
| 46 | +})() |
| 47 | +
|
| 48 | +*/ |
30 | 49 |
|
31 |
| -var ar = [5, 6, 7, 8, 1, 2, 12, 14] |
32 |
| -// Array before Sort |
33 |
| -console.log(ar) |
34 |
| -selectionSort(ar) |
35 |
| -// Array after sort |
36 |
| -console.log(ar) |
| 50 | +export { selectionSort } |
0 commit comments