Skip to content

Commit 8a6f082

Browse files
committed
latest file for selection sort
1 parent 8e5da55 commit 8a6f082

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

selection_sort_latest.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Selection Sort
2+
3+
# It is a simple algorithm.
4+
# Repeatedly selecting a smallest or largest element from the unsorted portion of the list nd moving it to the
5+
# sorted portion of the list.
6+
7+
# TC: O(n^2)
8+
# One loop to select an element of Array one by one = O(N)
9+
# Another loop to compare that element with every other Array element = O(N)
10+
11+
# SC: O(1)
12+
# only extra memory used is for temporary variables while swapping two values in Array
13+
14+
def selection_sort(arr):
15+
# Traverse through all array element
16+
for i in range(len(arr)):
17+
# Assume the current index is the minimum index
18+
min_idx = i
19+
# Find the minimum element from the unsorted part of the array
20+
for j in range(i + 1, (len(arr))):
21+
# If the smaller is found, update it with the minimum index
22+
if arr[j] < arr[min_idx]:
23+
min_idx = j
24+
# Swap the found minimum element with the first element
25+
arr[i], arr[min_idx] = arr[min_idx], arr[i]
26+
27+
28+
arr = [74, 35, 22, 32, 21]
29+
selection_sort(arr)
30+
print("Sorted array: ", arr)
31+

0 commit comments

Comments
 (0)