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

Outer loop selects position to fill. - Inner loop finds minimum element in unsorted part. - Swap places minimum with current index. - Together sorts array in ascending order. Conclusion: Shows how selection sort can be implemented in arrays.

Quick Links to Explore