|
4 | 4 | - I find the smallest value in this list and set it to index 0. |
5 | 5 | - Then I find the next smallest value and continue my search. |
6 | 6 |
|
| 7 | +```python |
| 8 | +def selection_sort(arr): |
| 9 | + |
| 10 | + # for every slot in array |
| 11 | + for fillslot in range(len(arr)-1,0,-1): |
| 12 | + positionOfMax = 0 |
| 13 | + |
| 14 | + # for every set of 0 to fillslot+1 |
| 15 | + for location in range(1,fillslot+1): |
| 16 | + # set maximum's location |
| 17 | + if arr[location]>arr[positionOfMax]: |
| 18 | + positionOfMax = location |
| 19 | + |
| 20 | + temp = arr[fillslot] |
| 21 | + arr[fillslot] = arr[positionOfMax] |
| 22 | + arr[positionOfMax] = temp |
| 23 | + return arr |
| 24 | + |
| 25 | +arr = [3,2,13,4,6,5,7,8,1,20] |
| 26 | +print("Output: ", selection_sort(arr)) |
| 27 | +``` |
| 28 | +output: |
| 29 | +``` |
| 30 | +[1, 2, 3, 4, 5, 6, 7, 8, 13, 20] |
| 31 | +``` |
| 32 | + |
| 33 | + |
7 | 34 | <img src="https://lh3.googleusercontent.com/proxy/jbSWXUD7nCXlB6UvnYwu70Uj5CrhrQWJs5JixA5vu7HD-yVxUF0yo29lUWu0-GI00cC1XPE1B43YsTPeHk2m0H5Bxd2cAg4Ju_4s4kYs-oT1mmKkR_E996kieZQOhNoqlVjmWDOTCMk"/> |
0 commit comments