Python Program for Selection Sort Algorithm.
Selection Sort is a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted part of the array and putting it at the beginning. It divides the array into two parts: the sorted part and the unsorted part. The algorithm finds the smallest element from the unsorted part and swaps it with the first unsorted element, incrementing the sorted part’s size by one.
Algorithm Steps:
- Start from the beginning of the list.
- Find the minimum element in the unsorted part.
- Swap it with the first unsorted element.
- Increment the sorted part’s size by one.
- Repeat steps 2-4 until the entire list is sorted.
Python Code Implementation for Selection Sort.
Here is an example of Selection Sort in Python:
# Python code for Selection Sort Algorithm def selection_sort(arr): n = len(arr) for i in range(n): min_idx = i for j in range(i + 1, n): if arr[j] < arr[min_idx]: min_idx = j arr[i], arr[min_idx] = arr[min_idx], arr[i] # Example usage: arr = [64, 34, 25, 12, 22, 11, 90] selection_sort(arr) print("Sorted array:", arr)
Sorted array: [11, 12, 22, 25, 34, 64, 90]
Time and Space Complexity.
- Time Complexity: O(n^2) as it involves nested loops iterating through the array, making it inefficient for larger datasets.
- Space Complexity: O(1) as Selection Sort operates in place, requiring only a constant amount of extra space for variables.
No comments:
Post a Comment