File tree Expand file tree Collapse file tree 2 files changed +45
-0
lines changed
Expand file tree Collapse file tree 2 files changed +45
-0
lines changed Original file line number Diff line number Diff line change @@ -14,6 +14,7 @@ This is my study repository.
1414* doubly linked list.
1515* recursion.
1616* bubble sort.
17+ * selection sort.
1718
1819
1920## Link
Original file line number Diff line number Diff line change 1+ #!/usr/bin/env python3
2+
3+ ##
4+ # Selection Sort
5+ ##
6+
7+ import numpy as np
8+
9+ def selection_sort (array ):
10+ """
11+ Sorts an array using the selection sort algorithm.
12+
13+ The selection sort algorithm repeatedly selects the smallest element
14+ from the unsorted portion of the list and swaps it with the element
15+ at the current position. This process continues until the entire array is sorted.
16+
17+ Parameters:
18+ array (numpy.ndarray): The array to be sorted.
19+
20+ Returns:
21+ numpy.ndarray: The sorted array.
22+ """
23+ n = len (array ) # Get the length of the array
24+
25+ # Loop over each element in the array
26+ for i in range (n ):
27+ id_minimum = i # Assume the current element is the minimum
28+
29+ # Traverse the unsorted portion of the array
30+ for j in range (i + 1 , n ):
31+ # Find the minimum element in the unsorted portion
32+ if array [id_minimum ] > array [j ]:
33+ id_minimum = j # Update the index of the minimum element
34+
35+ # Swap the found minimum element with the element at position i
36+ temp = array [i ]
37+ array [i ] = array [id_minimum ]
38+ array [id_minimum ] = temp
39+
40+ return array # Return the sorted array
41+
42+ # Example usage of the selection_sort function
43+ sorted_array = selection_sort (np .array ([15 , 34 , 8 , 3 ]))
44+ print ("Sorted array:" , sorted_array ) # Output: [ 3 8 15 34]
You can’t perform that action at this time.
0 commit comments