Experiment No.
: 9
9(a). Write a program to implement selection sort.
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting
the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted
element. This process continues until the entire array is sorted.
In this program, we use selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains
two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted. In every iteration of selection sort, the minimum element
(considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.
Time Complexity: O(n2).
Space Complexity: O(1).
Program :
def selection_sort(arr):
# Traverse through all elements in the array
for i in range(len(arr)):
# Find the minimum element in the remaining unsorted array
min_index = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[min_index]:
min_index = j
# Swap the found minimum element with the first element
arr[i], arr[min_index] = arr[min_index], arr[i]
numbers = [64, 34, 25, 12, 22, 11, 90]
print("Original array:", numbers)
selection_sort(numbers)
print("Sorted array:", numbers)
Output:
Original array: [64, 34, 25, 12, 22, 11, 90]
Sorted array: [11, 12, 22, 25, 34, 64, 90]
Viva Questions:
1. Can Selection Sort be considered stable or unstable?
2. Which collection does not allow duplicate members in python?
3. How can you create and use a Module in Python??
4. What is slicing in Python?
5. What are unit tests in Python?