9.1.2 Selection Sort
Selection sort is a fundamental sorting algorithm that is often taught as an introduction to the concept of sorting. It is an in-place comparison-based algorithm that divides the array into two parts: a sorted subarray and an unsorted subarray. The algorithm repeatedly selects the minimum (or maximum, depending on the sorting order) element from the unsorted subarray and moves it to the end of the sorted subarray. This process continues until the entire array is sorted.
How Selection Sort Works
Selection sort operates by maintaining two subarrays within the given array:
- Sorted Subarray: Initially empty and grows as elements are sorted and added.
- Unsorted Subarray: Initially contains all elements and shrinks as elements are sorted.
The algorithm works by iteratively selecting the smallest element from the unsorted subarray and swapping it with the first unsorted element, effectively growing the sorted subarray by one element with each iteration.
Step-by-Step Example
Consider the following example array:
// Example array
let arr = [64, 25, 12, 22, 11];
Let’s walk through the selection sort process:
-
Initial Array: [64, 25, 12, 22, 11]
- The first element of the unsorted subarray is 64.
- Find the minimum element in the unsorted subarray
[64, 25, 12, 22, 11]
, which is 11.
- Swap 11 with 64.
-
Array After First Pass: [11, 25, 12, 22, 64]
- The first element of the unsorted subarray is 25.
- Find the minimum element in the unsorted subarray
[25, 12, 22, 64]
, which is 12.
- Swap 12 with 25.
-
Array After Second Pass: [11, 12, 25, 22, 64]
- The first element of the unsorted subarray is 25.
- Find the minimum element in the unsorted subarray
[25, 22, 64]
, which is 22.
- Swap 22 with 25.
-
Array After Third Pass: [11, 12, 22, 25, 64]
- The first element of the unsorted subarray is 25.
- Find the minimum element in the unsorted subarray
[25, 64]
, which is 25.
- No swap needed as 25 is already in place.
-
Array After Fourth Pass: [11, 12, 22, 25, 64]
- The array is now fully sorted.
Implementing Selection Sort in JavaScript
The following JavaScript function implements the selection sort algorithm:
function selectionSort(arr) {
let n = arr.length;
for (let i = 0; i < n - 1; i++) {
let minIndex = i;
// Find the minimum element in the unsorted portion
for (let j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap the found minimum element with the first unsorted element
if (minIndex !== i) {
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
}
}
return arr;
}
// Example usage
let array = [64, 25, 12, 22, 11];
console.log(selectionSort(array)); // Output: [11, 12, 22, 25, 64]
Analyzing the Time and Space Complexity
Time Complexity
- Worst-case time complexity: O(n²)
- Average-case time complexity: O(n²)
- Best-case time complexity: O(n²)
The time complexity of selection sort is O(n²) for all cases because it always performs n(n-1)/2 comparisons, regardless of the initial arrangement of elements.
Space Complexity
Selection sort is an in-place sorting algorithm, meaning it requires a constant amount of additional memory space. Therefore, its space complexity is O(1).
Comparison with Bubble Sort
Selection sort and bubble sort are both simple, comparison-based sorting algorithms with a time complexity of O(n²). However, selection sort generally performs better than bubble sort in scenarios with fewer swaps. This is because selection sort minimizes the number of swaps by only swapping once per pass through the array, whereas bubble sort can perform multiple swaps per pass.
Practical Considerations and Use Cases
Selection sort is not suitable for large datasets due to its quadratic time complexity. However, it can be useful in scenarios where memory space is limited, and the number of swaps needs to be minimized. It is also a good educational tool for understanding the basics of sorting algorithms.
Visualizing Selection Sort
To better understand the selection sort process, consider the following flowchart that illustrates the algorithm’s steps:
graph TD;
A[Start] --> B[Set minIndex to i]
B --> C{Is j < n?}
C -->|Yes| D{arr[j] < arr[minIndex]?}
D -->|Yes| E[Set minIndex to j]
D -->|No| F[Increment j]
E --> F
F --> C
C -->|No| G{minIndex != i?}
G -->|Yes| H[Swap arr[i] and arr[minIndex]]
G -->|No| I[Increment i]
H --> I
I --> J{Is i < n-1?}
J -->|Yes| B
J -->|No| K[End]
Best Practices and Common Pitfalls
-
Best Practices:
- Use selection sort for small datasets or when memory usage is a critical constraint.
- Ensure the array is not modified during the sorting process to avoid unexpected behavior.
-
Common Pitfalls:
- Forgetting to swap elements when the minimum index changes can lead to incorrect sorting.
- Misunderstanding the algorithm’s time complexity and applying it to large datasets can result in inefficient performance.
Optimization Tips
While selection sort is not the most efficient algorithm for large datasets, understanding its mechanics can help in optimizing other algorithms. For instance, minimizing swaps can be a useful strategy in algorithms where swap operations are costly.
Further Reading and Resources
For those interested in exploring more about sorting algorithms and their applications, consider the following resources:
Quiz Time!
### What is the time complexity of selection sort in the best case?
- [x] O(n²)
- [ ] O(n log n)
- [ ] O(n)
- [ ] O(log n)
> **Explanation:** Selection sort always performs n(n-1)/2 comparisons, regardless of the input, resulting in a time complexity of O(n²) in all cases.
### How does selection sort differ from bubble sort in terms of swaps?
- [x] Selection sort minimizes the number of swaps.
- [ ] Bubble sort minimizes the number of swaps.
- [ ] Both perform the same number of swaps.
- [ ] Neither performs swaps.
> **Explanation:** Selection sort performs a single swap per pass, whereas bubble sort may perform multiple swaps per pass.
### What is the space complexity of selection sort?
- [x] O(1)
- [ ] O(n)
- [ ] O(n log n)
- [ ] O(log n)
> **Explanation:** Selection sort is an in-place algorithm, requiring only a constant amount of additional memory space.
### Which of the following is a characteristic of selection sort?
- [x] It is an in-place sorting algorithm.
- [ ] It is a stable sorting algorithm.
- [ ] It has a time complexity of O(n log n).
- [ ] It requires additional memory proportional to the input size.
> **Explanation:** Selection sort is in-place but not stable, and it has a time complexity of O(n²).
### In selection sort, what is the main operation performed during each iteration?
- [x] Finding the minimum element in the unsorted subarray.
- [ ] Merging two sorted subarrays.
- [ ] Dividing the array into smaller parts.
- [ ] Inserting an element into its correct position.
> **Explanation:** The main operation in selection sort is finding the minimum element in the unsorted subarray and swapping it with the first unsorted element.
### What is the primary advantage of selection sort over bubble sort?
- [x] Fewer swaps are performed.
- [ ] It is faster for large datasets.
- [ ] It is more stable.
- [ ] It uses less memory.
> **Explanation:** Selection sort performs fewer swaps than bubble sort, which can be advantageous when swap operations are costly.
### Which of the following scenarios is selection sort most suitable for?
- [x] Small datasets with limited memory.
- [ ] Large datasets requiring fast sorting.
- [ ] Datasets where stability is critical.
- [ ] Datasets with a large number of duplicate elements.
> **Explanation:** Selection sort is suitable for small datasets where memory usage is a constraint.
### What is the main disadvantage of selection sort?
- [x] It has a high time complexity of O(n²).
- [ ] It requires additional memory.
- [ ] It is not in-place.
- [ ] It is unstable.
> **Explanation:** The main disadvantage of selection sort is its O(n²) time complexity, making it inefficient for large datasets.
### Which part of the array does selection sort initially consider as sorted?
- [x] An empty subarray.
- [ ] The entire array.
- [ ] The first half of the array.
- [ ] The last half of the array.
> **Explanation:** Selection sort starts with an empty sorted subarray and grows it by adding one element at a time.
### True or False: Selection sort is a stable sorting algorithm.
- [ ] True
- [x] False
> **Explanation:** Selection sort is not stable because it may change the relative order of equal elements.