Created
November 14, 2021 10:48
-
-
Save anchitarnav/fd7fd3fd723b506a4c3d04dcb9578144 to your computer and use it in GitHub Desktop.
Selection Sort Python implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Selection Sort --> Python Implementation | |
| # The smallest element from the UNSORTED array shall always be on the right of the SORTED array | |
| # This is similar to heap sort where the smallest element comes out everytime. | |
| def selection_sort(array: list): | |
| for smallest_unsorted in range(0, len(array)): | |
| smallest_index = smallest_unsorted | |
| smallest_element = array[smallest_index] | |
| for i in range(smallest_index, len(array)): | |
| if array[i] < smallest_element: | |
| smallest_element = array[i] | |
| smallest_index = i | |
| # swap | |
| array[smallest_unsorted], array[smallest_index] = array[smallest_index], array[smallest_unsorted] | |
| if __name__ == '__main__': | |
| import random, copy | |
| arr = [num for num in range(10)] | |
| random.shuffle(arr) | |
| print(f"Unsorted => {arr}") | |
| selection_sort(arr) | |
| print(f"Sorted => {arr}") | |
| assert arr == sorted(copy.deepcopy(arr)), "Not Sorted properly" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment