- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathselectionSort.py
47 lines (33 loc) · 1.15 KB
/
selectionSort.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# program for selection sort
#selections sort takes O(n^2) time complexity
#program starts from here
defselectionSort( itemsList ):
n=len( itemsList )
foriinrange( n-1 ):
minValueIndex=i
forjinrange( i+1, n ):
ifitemsList[j] <itemsList[minValueIndex] :
minValueIndex=j
ifminValueIndex!=i :
temp=itemsList[i]
itemsList[i] =itemsList[minValueIndex]
itemsList[minValueIndex] =temp
returnitemsList
# Selection sort in Python
# time complexity O(n^2)
#sorting by finding min_index
#CODE =
defselectionSort(array, size):
forindinrange(size):
min_index=ind
forjinrange(ind+1, size):
# select the minimum element in every iteration
ifarray[j] <array[min_index]:
min_index=j
# swapping the elements to sort the array
(array[ind], array[min_index]) = (array[min_index], array[ind])
arr= [-2, 45, 0, 11, -9,88,-97,-202,747]
size=len(arr)
selectionSort(arr, size)
print('The array after sorting in Ascending Order by selection sort is:')
print(arr)