Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 76e2cf2

Browse files
Selection Sort
1 parent 5492cd1 commit 76e2cf2

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,5 @@ Data Structures and Algorithms Patterns implemented in Python.
2525
- [x] [Sorting Alogorithms](Sorting-Algo)
2626
- [x] [Bubble Sort](Sorting-Algo/bubblesort.py)
2727
- [x] [Insertion Sort](Sorting-Algo/insertionsort.py)
28+
- [x] [Selection Sort](Sorting-Algo/selectionsort.py)
2829

‎Sorting-Algo/selectionsort.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
'''
2+
Selection Sort
3+
4+
Selection sort is a sorting algorithm that selects the smallest element from an unsorted list in each iteration and places that element at the beginning of the unsorted list.
5+
6+
Time Complexity - O(n^2)
7+
'''
8+
def selectionSort(list, length):
9+
10+
for step in range(length):
11+
min_idx = step
12+
13+
for i in range(step + 1, length):
14+
15+
# to sort in descending order, change > to < in this line
16+
# select the minimum element in each loop
17+
if list[i] < list[min_idx]:
18+
min_idx = i
19+
20+
# put min at the correct position
21+
(list[step], list[min_idx]) = (list[min_idx], list[step])
22+
23+
24+
array = [-2, 45, 0, 11, -9]
25+
length = len(array)
26+
selectionSort(array, length)
27+
print(array) #[-9, -2, 0, 11, 45]

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /