The Selection Sort algorithm divides the array into two parts: the sorted part and the unsorted part. Initially, the sorted part is empty, and the unsorted part contains all the elements. The algorithm works by finding the smallest (or largest, depending on sorting order) element from the unsorted part and swapping it with the first element of the unsorted part. This process continues until the entire array is sorted.
#Suppose we have the following array: arr = [64, 25, 12, 22, 11]
Array after the first pass: [11, 25, 12, 22, 64]
Array after the second pass: [11, 12, 25, 22, 64]
Array after the third pass: [11, 12, 22, 25, 64]
Final sorted array: [11, 12, 22, 25, 64]
def selection_sort(arr): # Traverse through all array elements for i in range(len(arr)): # Find the minimum element in the remaining unsorted part min_index = i for j in range(i 1, len(arr)): if arr[j]Sorted array: [11, 12, 22, 25, 64]
Time Complexity of Selection Sort:
Best Case: O(n²)
Average Case: O(n²)
Worst Case: O(n²)
Even though Selection Sort performs well for small datasets, it is not ideal for larger arrays because its time complexity is O(n²). However, it is easy to implement and can be useful in cases where memory is a concern, as Selection Sort is in-place (requires no additional memory).
Advantages:
Simple to understand and implement.
Performs well on small lists.
Doesn't require extra memory since it sorts the array in place.
Disadvantages:
Inefficient for large datasets due to its O(n²) time complexity.
It isn't a stable sorting algorithm, meaning equal elements might not preserve their order relative to each other.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3