Python Data Structures and Algorithms: Sort a list of elements using Selection sort
Python Search and Sorting : Exercise-20 with Solution
Write a Python program to sort a list of elements using Selection sort.
According to Wikipedia "In computer science, selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) time complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort".
def selection_sort(nums): for i, n in enumerate(nums): mn = min(range(i,len(nums)), key=nums.__getitem__) nums[i], nums[mn] = nums[mn], n return nums user_input = input("Input numbers separated by a comma:\n").strip() nums = [int(item) for item in user_input.split(',')] print(selection_sort(nums))
Input numbers separated by a comma: 15, 79, 25, 37, 68 [15, 25, 37, 68, 79]
Python Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
- New Content published on w3resource :
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework