Skip to content

Commit

Permalink
feat: Implement Selection Sort
Browse files Browse the repository at this point in the history
  • Loading branch information
Shaban-Eissa committed Jun 5, 2024
1 parent 1e24e44 commit 0074c14
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions 44.implement-Selection-Sort.md
Original file line number Diff line number Diff line change
@@ -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.

0 comments on commit 0074c14

Please sign in to comment.