Skip to content
This repository was archived by the owner on Apr 1, 2021. It is now read-only.
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions Algorithms-Selection-Sort.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Algorithm Selection Sort

The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array.
1. The subarray which is already sorted.
2. Remaining subarray which is unsorted.

In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.

## Example
[Animation of SelectionSort](http://www.sorting-algorithms.com/selection-sort)

```
arr[] = 64 25 12 22 11

# Placing the minimum element in arr[0...4] in the beginning
11 25 12 22 64

# Placing the minimum element in arr[1...4] in the beginning
11 12 25 22 64

# Placing the minimum element in arr[2...4] in the beginning
11 12 22 25 64

# Placing the minimum element in arr[3...4] in the beginning
11 12 22 25 64
```

#### Python Implementation

```python
def selection_sort(arr):
for i in range(len(arr)):
min_x = i
for j in range(i+1,len(arr)):
if arr[j] < arr[min_x]:
min_x = j
arr[min_x], arr[i] = arr[i], arr[min_x]

arr = [64, 25, 12, 22, 11]
selection_sort(arr)
print(arr) # Prints [11, 12, 22, 25, 64]
```

:rocket: [Run Code](https://repl.it/CXwQ)

#### [Complexity of Algorithm](https://www.freecodecamp.com/videos/big-o-notation-what-it-is-and-why-you-should-care)

**Time Complexity:** O(n*n) Due to the two nested loops.