Tutorialspoint
Problem
Solution
Submissions

Selection Sort

Certification: Basic Level Accuracy: 40% Submissions: 5 Points: 5

Write a Java program to implement the Selection Sort algorithm to sort an array of integers in ascending order.

Example 1
  • Input: nums = [64, 25, 12, 22, 11]
  • Output: [11, 12, 22, 25, 64]
  • Explanation:
    • Each pass selects the minimum element and swaps it
Example 2
  • Input: nums = [5, 1, 4, 2, 8]
  • Output: [1, 2, 4, 5, 8]
Constraints
  • 1 ≤ nums.length ≤ 10^4
  • -10^5 ≤ nums[i] ≤ 10^5
  • Time Complexity: O(n²)
  • Space Complexity: O(1)
ArraysAlgorithmseBayTutorix
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 input array into two subarrays: sorted and unsorted.
  • Initially, the sorted subarray is empty and the unsorted subarray is the entire input array.
  • Find the smallest element in the unsorted subarray.
  • Swap the smallest element with the first element of the unsorted subarray.
  • Move the boundary between sorted and unsorted subarrays one element to the right.
  • Repeat until the entire array is sorted.

Steps to solve by this approach:

 Step 1: Iterate through the array from index 0 to n-2 (where n is the array length).

 Step 2: For each iteration, assume the current element is the minimum.
 Step 3: Search for a smaller element in the remaining unsorted part of the array.
 Step 4: If a smaller element is found, update the minimum index.
 Step 5: After the inner loop, swap the minimum element with the element at the current position.
 Step 6: Move to the next position and repeat until the entire array is sorted.
 Step 7: The array is now sorted in ascending order.

Submitted Code :