Tutorialspoint
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]
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]
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)
ArraysAlgorithmsMicrosoftFacebook
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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.

Steps to solve by this approach:

 Step 1: Divide the array into sorted and unsorted regions.

 Step 2: Find the minimum element in the unsorted region.
 Step 3: Swap the minimum element with the first element of unsorted region.
 Step 4: Expand the sorted region by one element.
 Step 5: Repeat until the entire array is sorted.
 Step 6: Return the sorted array.

Submitted Code :