
Problem
Solution
Submissions
Selection Sort
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C++ program that implements the selection sort algorithm. The program should take an unsorted array of integers and sort it in ascending order by repeatedly finding the minimum element from the unsorted part and putting it at the beginning.
Example 1
- Input: array = [64, 25, 12, 22, 11]
- Output: [11, 12, 22, 25, 64]
- Explanation:
- Step 1: Find minimum in positions 0-4: 11 at index 4
- Swap 64 and 11: [11, 25, 12, 22, 64]
- Step 2: Find minimum in positions 1-4: 12 at index 2
- Swap 25 and 12: [11, 12, 25, 22, 64]
- Step 3: Find minimum in positions 2-4: 22 at index 3
- Swap 25 and 22: [11, 12, 22, 25, 64]
- Step 4: Find minimum in positions 3-4: 25 at index 3
- No swap needed
- Step 5: Return sorted array [11, 12, 22, 25, 64]
- Step 1: Find minimum in positions 0-4: 11 at index 4
Example 2
- Input: array = [5, 5, 4, 3, 8]
- Output: [3, 4, 5, 5, 8]
- Explanation:
- Step 1: Find minimum in positions 0-4: 3 at index 3
- Swap 5 and 3: [3, 5, 4, 5, 8]
- Step 2: Find minimum in positions 1-4: 4 at index 2
- Swap 5 and 4: [3, 4, 5, 5, 8]
- Step 3: Find minimum in positions 2-4: 5 at index 2
- No swap needed
- Step 4: Find minimum in positions 3-4: 5 at index 3
- No swap needed
- Step 5: Return sorted array [3, 4, 5, 5, 8]
- Step 1: Find minimum in positions 0-4: 3 at index 3
Constraints
- 1 ≤ array.length ≤ 10^3
- -10^6 ≤ array[i] ≤ 10^6
- Time Complexity: O(n²), where n is the length of the array
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Divide the array into two parts: sorted and unsorted.
- Initially, the sorted part is empty and the unsorted part is the entire array.
- Find the minimum element in the unsorted part.
- Swap the minimum element with the first element of the unsorted part.
- Expand the sorted part to include the newly placed element.
- Repeat until the entire array is sorted.