To write a program to perform selection sort and insertion sort using python programming.
- Hardware – PCs
- Anaconda – Python 3.7 Installation / Moodle-Code Runner
- Set the first unsorted element as the minimum
- For each of the unsorted elements, check if the element < current minimum.
- If yes, set the element as the new minimum.
- Swap minimum with first unsorted position.
- Repeat the steps 2 and 3 for all the elements in the array.
- Set the first element as sorted element j.
- For each unsorted element X, check if current sorted element j >X.
- If yes, move sorted element to the right by 1.
- Break the loop and insert X.
- Repeat the steps 2 to 4 for sorting all the elements in the array.
i) #Selection Sort
Program to sort the elements in the list using the Selection Sort algorithm.
Developed by: Kabilan V
RegisterNumber: 212222100018
def selection_sort(nums):
n=len(nums)
for i in range(n):
min=i
for j in range(i+1,n):
if(nums[j]<nums[min]):
min=j
(nums[i],nums[min])=(nums[min],nums[i])
return nums
list_of_nums = eval(input())
new_nums=selection_sort(list_of_nums)
print(new_nums)
ii) #Insertion Sort
Program to sort the elements in the list using the Insertion Sort algorithm.
Developed by: Kabilan V
RegisterNumber: 212222100018
def insertion_sort(nums):
for i in range(1,len(nums)):
key=nums[i]
j=i-1
while j>=0 and key<nums[j]:
nums[j+1]=nums[j]
j-=1
nums[j+1]=key
return nums
list_of_nums = eval(input())
new_nums=insertion_sort(list_of_nums)
print(new_nums)
1.selection sort
2.insertion sort
Thus the program is written to perform selection sort and insertion sort using python programming.