Given an array of integers nums, sort the array in non-decreasing order using the selection sort algorithm and return the sorted array.
A sorted array in non-decreasing order is an array where each element is greater than or equal to all previous elements in the array.
Input: nums = [7, 4, 1, 5, 3]
Output: [1, 3, 4, 5, 7]
Explanation: 1 <= 3 <= 4 <= 5 <= 7.
Thus the array is sorted in non-decreasing order.
Input: nums = [5, 4, 4, 1, 1]
Output: [1, 1, 4, 4, 5]
Explanation: 1 <= 1 <= 4 <= 4 <= 5.
Thus the array is sorted in non-decreasing order.
Input: nums = [3, 2, 3, 4, 5]
The selection sort algorithm sorts an array by repeatedly finding the minimum element from the unsorted part and putting it at the beginning. The largest element will end up at the last index of the array.
i
from 0 to n-1.i
to n-1 using an inner loop.i
.#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Function for selection sort
vector<int> selectionSort(vector<int>& nums) {
// Loop through the unsorted array
for (int i = 0; i < nums.size() - 1; i++) {
/*Assume the current
index is the smallest*/
int minIndex = i;
// Find the index of the smallest element
for (int j = i + 1; j <nums.size(); j++) {
/*Update minIndex if smaller
element is found */
if (nums[j] < nums[minIndex]) {
minIndex = j;
}
}
// Swap only if minIndex is changed
if (minIndex != i) {
swap(nums[minIndex], nums[i]);
}
}
return nums;
}
};
int main() {
vector<int> arr = {7, 5, 9, 2, 8};
cout << "Original array: ";
for (int num : arr) {
cout << num << " ";
}
cout << endl;
// Create an instance of the Solution class
Solution s1;
// function call for Selection Sort
vector<int> sortedArr = s1.selectionSort(arr);
cout << "Sorted array: ";
for (int num : sortedArr) {
cout << num << " ";
}
cout << endl;
return 0;
}
import java.util.*;
class Solution {
public int[] selectionSort(int[] nums) {
// Loop through unsorted part of the array (0 to n-2)
for (int i = 0; i < nums.length - 1; i++) {
/*Assume current element
is the minimum*/
int minIndex = i;
// Find actual minimum in unsorted part (i+1 to n-1)
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] < nums[minIndex]) {
minIndex = j;
}
}
// Swap only if minIndex changed
if (minIndex != i) {
int temp = nums[i];
nums[i] = nums[minIndex];
nums[minIndex] = temp;
}
}
return nums;
}
}
public class Main {
public static void main(String[] args) {
int[] arr = {7, 5, 9, 2, 8};
System.out.print("Original array: ");
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
// create an instance of solution class
Solution solution = new Solution();
// function call for selection sort
int[] sortedArr = solution.selectionSort(arr);
System.out.print("Sorted array: ");
for (int num : sortedArr) {
System.out.print(num + " ");
}
System.out.println();
}
}
class Solution:
def selectionSort(self, nums):
# Loop through unsorted part
# of the array (0 to n-2)
for i in range(len(nums) - 1):
''' Assume current
element is minimum '''
min_index = i
'''Find actual minimum in
unsorted part (i+1 to n-1) '''
for j in range(i + 1, len(nums)):
if nums[j] < nums[min_index]:
min_index = j
''' Swap only if minIndex
changed (optimization) '''
if min_index != i:
nums[i], nums[min_index] = nums[min_index], nums[i]
return nums
# Main function to test the selection sort
if __name__ == "__main__":
solution = Solution()
nums = [64, 25, 12, 22, 11]
sorted_nums = solution.selectionSort(nums)
print("Sorted array:", sorted_nums)
class Solution {
selectionSort(nums) {
// Loop through unsorted part of the array (0 to n-2)
for (let i = 0; i < nums.length - 1; i++) {
// Assume current element is the minimum
let minIndex = i;
// Find actual minimum in unsorted part (i+1 to n-1)
for (let j = i + 1; j < nums.length; j++) {
if (nums[j] < nums[minIndex]) {
minIndex = j;
}
}
// Swap only if minIndex changed (optimization)
if (minIndex != i) {
[nums[i], nums[minIndex]] = [nums[minIndex], nums[i]];
}
}
return nums;
}
}
// Example usage:
const solution = new Solution();
console.log(solution.selectionSort([64, 25, 12, 22, 11]));
Time Complexity: O(N2) where N is the length of the input array. The outer loop runs through each element, and the inner loop finds the smallest element in the unsorted portion of the array.
Space Complexity: O(1) as it is an in-place sorting algorithm and does not require additional storage proportional to the input size.
Q: Can selection sort handle duplicate elements properly?
A: Yes, selection sort can handle duplicate elements effectively. During each iteration, the algorithm identifies the smallest element in the unsorted portion, even if duplicates exist. The duplicates are treated like any other elements and sorted based on their relative positions, preserving the order among equal elements.
Q: What happens if the array is already sorted? Is it still efficient?
A: Selection sort doesn’t check if the array is already sorted—it always performs O(n2) comparisons because the algorithm doesn’t adapt to sorted inputs. While no swaps may occur if the array is sorted, the comparisons in the inner loop are still executed, making it inefficient for pre-sorted data.
Q: Can you modify the selection sort algorithm to sort the array in descending order? What changes would you make?
A: To sort the array in descending order, you need to modify the algorithm to find the largest element in the unsorted portion during each iteration instead of the smallest. Then, place this largest element at the current position in the sorted portion. Here’s the adjusted approach: In the inner loop, compare elements to find the maximum instead of the minimum. Swap the maximum element with the current index of the sorted portion. Example: Input: [4, 2, 9, 1] Process: Find the largest (9) and swap with the first element: [9, 2, 4, 1]. Find the next largest (4) in the unsorted portion and swap: [9, 4, 2, 1]. Continue until sorted in descending order: [9, 4, 2, 1]. This change preserves the same O(n2) time complexity but adapts the algorithm for descending order.
Q: Selection sort has O(n2) time complexity. Can you identify a scenario where selection sort might still be a preferred choice?
A: 1. Selection sort works in-place and uses O(1) extra memory. For systems with strict memory limitations, it is a viable choice. 2. For small arrays (e.g., fewer than 10 elements), the simplicity of selection sort can outweigh its inefficiency. The overhead of more complex algorithms, like merge sort or quicksort, might not be justified. Example: Sorting [5, 2, 1] in embedded systems with limited RAM can efficiently use selection sort.
Q: How does selection sort compare to insertion sort in terms of performance and use cases? Can you analyze and contrast them?
A: Time Complexity: Both have O(n^2) worst-case time complexity. However, insertion sort can outperform selection sort for nearly sorted arrays because it minimizes shifts, while selection sort always performs n−1 comparisons in the inner loop, regardless of the array's state. Swaps vs. Shifts: Selection sort minimizes swaps (n−1 swaps in total), making it suitable for situations where swap costs are high (e.g., flash memory). Insertion sort involves more shifts, especially for large unsorted portions. Example: For an array like [2, 3, 4, 5, 1], insertion sort will quickly sort it with fewer operations because most elements are already in place. In contrast, selection sort performs the same number of comparisons regardless of the initial order, making it less efficient in this case.