Selection Sort Implementation
This program sorts an array using selection sort algorithm.
Problem Statement
Write a Java program to sort an integer array using selection sort.
Source Code
| 1 | public class SelectionSort { |
| 2 | public static void main(String[] args) { |
| 3 | int[] arr = {29, 10, 14, 37, 13}; |
| 4 | for(int i=0; i<arr.length-1; i++) { |
| 5 | int minIndex = i; |
| 6 | for(int j=i+1; j<arr.length; j++) { |
| 7 | if(arr[j] < arr[minIndex]) minIndex = j; |
| 8 | } |
| 9 | int temp = arr[minIndex]; |
| 10 | arr[minIndex] = arr[i]; |
| 11 | arr[i] = temp; |
| 12 | } |
| 13 | System.out.print("Sorted array: "); |
| 14 | for(int num : arr) System.out.print(num + " "); |
| 15 | } |
| 16 | } |
Program Output
Sorted array: 10 13 14 29 37
Explanation
The outer loop selects the position to fill, and the inner loop finds the minimum element in the remaining unsorted part, swapping it into the current position, so the array is sorted in ascending order.