From 0074c1458e1f20aad00b6135a64dd57810fbe71a Mon Sep 17 00:00:00 2001 From: Shaban-Eissa Date: Wed, 5 Jun 2024 15:35:08 +0300 Subject: [PATCH] feat: Implement Selection Sort --- 44.implement-Selection-Sort.md | 50 ++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 44.implement-Selection-Sort.md diff --git a/44.implement-Selection-Sort.md b/44.implement-Selection-Sort.md new file mode 100644 index 0000000..56c542b --- /dev/null +++ b/44.implement-Selection-Sort.md @@ -0,0 +1,50 @@ +# 44. implement Selection Sort +Selection Sort is a simple comparison-based sorting algorithm. It divides the input list into two parts: a sorted sublist of items which is built up from left to right at the front (left) of the list, and a sublist of the remaining unsorted items that occupy the rest of the list. The algorithm repeatedly selects the smallest (or largest, depending on sorting order) element from the unsorted sublist, swaps it with the leftmost unsorted element, and moves the sublist boundaries one element to the right. + + +### Problem + +https://bigfrontend.dev/problem/implement-Selection-Sort + +# + +### Problem Description + +Even for Front-End Engineer, it is a must to understand how basic sorting algorithms work. + +Now you are asked to implement [Selection sort](https://en.wikipedia.org/wiki/Selection_sort), which sorts an integer array in ascending order. + +Do it **in-place**, no need to return anything. + +**Follow-up** + +What is time cost for average / worst case ? Is it stable? + +# + +### Solution + +```js +/** + * @param {number[]} arr + */ +function selectionSort(arr) { + for (let i = 0; i < arr.length; i++) { + let smallestIndex = i; + for (let j = i + 1; j < arr.length; j++) { + if (arr[j] < arr[smallestIndex]) { + smallestIndex = j; + } + } + if (smallestIndex !== i) { + [arr[smallestIndex], arr[i]] = [arr[i], arr[smallestIndex]]; + } + } +} +``` + +#### Use Cases: + +1. **Small Data Sets**: Suitable for small datasets where the overhead of more complex algorithms is not justified. +2. **Memory-Constrained Environments**: Due to its in-place nature, it is useful when memory space is at a premium. +3. **Simple Requirements**: When the simplicity of implementation is more important than performance. \ No newline at end of file