|
1 | | -# Selection sort in Python |
2 | | -# time complexity O(n*n) |
3 | | -#sorting by finding min_index |
| 1 | +def selectionSort(array): |
| 2 | + size = len(array) |
| 3 | + for ind in range(size): |
| 4 | + min_index = ind |
4 | 5 |
|
5 | | -def selectionSort(array, size): |
6 | | - |
7 | | - for ind in range(size): |
8 | | - min_index = ind |
| 6 | + for j in range(ind + 1, size): |
| 7 | + # select the minimum element in every iteration |
| 8 | + if array[j] < array[min_index]: |
| 9 | + min_index = j |
| 10 | + # swapping the elements to sort the array |
| 11 | + (array[ind], array[min_index]) = (array[min_index], array[ind]) |
9 | 12 |
|
10 | | - for j in range(ind + 1, size): |
11 | | - # select the minimum element in every iteration |
12 | | - if array[j] < array[min_index]: |
13 | | - min_index = j |
14 | | - # swapping the elements to sort the array |
15 | | - (array[ind], array[min_index]) = (array[min_index], array[ind]) |
| 13 | +def main(): |
| 14 | + arr = [] |
| 15 | + n = int(input("Enter the number of elements: ")) |
| 16 | + for i in range(n): |
| 17 | + element = int(input(f"Enter element {i+1}: ")) |
| 18 | + arr.append(element) |
| 19 | + |
| 20 | + selectionSort(arr) |
| 21 | + print('The array after sorting in Ascending Order by selection sort is:') |
| 22 | + print(arr) |
| 23 | + |
| 24 | +if __name__ == "__main__": |
| 25 | + main() |
16 | 26 |
|
17 | | -arr = [-2, 45, 0, 11, -9,88,-97,-202,747] |
18 | | -size = len(arr) |
19 | | -selectionSort(arr, size) |
20 | | -print('The array after sorting in Ascending Order by selection sort is:') |
21 | | -print(arr) |
|
0 commit comments