Skip to content

Commit 9bec267

Browse files
authored
feat: add selection sort. closes TheAlgorithms#95 (TheAlgorithms#96)
1 parent b1ac5d6 commit 9bec267

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

sorts/selection_sort.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* @function selectionSort
3+
* @description Selection sort algorithm is simple and easy. In selection sort the smallest value is selected from the unsorted part and placed at the beginning. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high.
4+
* @Complexity_Analysis
5+
* Space complexity - O(1)
6+
* Time complexity
7+
*      Best case   -   O(n^2)
8+
* The best case occurs when an array is already sorted.
9+
*      Worst case  -   O(n^2)
10+
* The worst case occurs when an array is reverse sorted.
11+
*      Average case -  O(n^2)
12+
* The average case occurs when an array is reverse sorted.
13+
*
14+
* @param {number[]} items - The input array
15+
* @return {number[]} - The sorted array.
16+
* @see [Selection Sort](https://www.javatpoint.com/selection-sort)
17+
* @example selectionSort([12, 29, 25, 8, 32, 17, 40]) = [8, 12, 17, 25, 29, 32, 40]
18+
*/
19+
20+
export const selectionSort = (items: number[]) => {
21+
for (let i = 0; i < items.length; i++) {
22+
let min = i;
23+
for (let j = i + 1; j < items.length; j++) {
24+
if (items[j] < items[min]) {
25+
min = j;
26+
}
27+
}
28+
if (i !== min) {
29+
[items[i], items[min]] = [items[min], items[i]];
30+
}
31+
}
32+
return items;
33+
};

sorts/test/selection_sort.test.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { selectionSort } from "../selection_sort";
2+
3+
describe("Testing Selection sort", () => {
4+
const testCases: number[][] = [];
5+
6+
for (let i = 0; i < 10; i++) {
7+
const arr = [];
8+
for (let j = 0; j < 100; j++) {
9+
arr.push(Math.floor(Math.random() * 100));
10+
}
11+
testCases.push(arr);
12+
}
13+
test.each(testCases)(
14+
"should return the correct value for test case: %#",
15+
(...arr: number[]) => {
16+
expect(selectionSort([...arr])).toStrictEqual(
17+
[...arr].sort((a: number, b: number) => a - b)
18+
);
19+
}
20+
);
21+
});

0 commit comments

Comments
 (0)