Skip to content

Commit 35e4b79

Browse files
committed
Add Selection sort
1 parent 76ffd09 commit 35e4b79

2 files changed

Lines changed: 31 additions & 8 deletions

File tree

SortingAlgorithms/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Soritng Algorithms in JavaScript
2+
3+
Bubble, Insertion, Selection and Merge sort.

SortingAlgorithms/index.js

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,18 @@ insertionSort = (array) => {
2626
return array
2727
}
2828

29+
selectionSort = (array) => {
30+
for (let i = 0; i < array.length - 1; i++) {
31+
let minIndex = i;
32+
for (let j = i + 1; j < array.length; j++) {
33+
if (array[j] < array[minIndex]) {
34+
minIndex = j;
35+
}
36+
}
37+
[array[i], array[minIndex]] = [array[minIndex], array[i]];
38+
}
39+
return array;
40+
}
2941
/* quickSortPartition = (array, left = 0, right = array.length - 1) => {
3042
let pivot = array[Math.floor((right + left) / 2)]
3143
let low = left
@@ -73,11 +85,11 @@ merge = (arr1, arr2) => {
7385
return sorted.concat(arr1.slice().concat(arr2.slice()));
7486
}
7587

76-
mergeSort = arr => {
77-
if (arr.length <= 1) return arr
78-
let mid = Math.floor(arr.length / 2),
79-
left = mergeSort(arr.slice(0, mid)),
80-
right = mergeSort(arr.slice(mid));
88+
mergeSort = (array) => {
89+
if (array.length <= 1) return array
90+
let mid = Math.floor(array.length / 2),
91+
left = mergeSort(array.slice(0, mid)),
92+
right = mergeSort(array.slice(mid));
8193

8294
return merge(left, right);
8395
}
@@ -108,12 +120,20 @@ const t3 = performance.now();
108120
console.log(`Insertion sort: ${t3 - t2} milliseconds.`);
109121
console.log(insertionArray)
110122

123+
console.log("SELECTION---------------------------")
124+
let selectionArray = buildAarray(20)
125+
console.log(selectionArray)
126+
const t4 = performance.now();
127+
selectionArray = selectionSort(selectionArray)
128+
const t5 = performance.now();
129+
console.log(`Selection sort: ${t3 - t2} milliseconds.`);
130+
console.log(selectionArray)
131+
111132
console.log("MERGE---------------------------")
112133
let mergeArray = buildAarray(20)
113134
console.log(mergeArray)
114-
const t4 = performance.now();
135+
const t6 = performance.now();
115136
mergeArray = mergeSort(mergeArray)
116-
const t5 = performance.now();
137+
const t7 = performance.now();
117138
console.log(`Merge sort: ${t5 - t4} milliseconds.`);
118139
console.log(mergeArray)
119-

0 commit comments

Comments
 (0)