# Java code for Selection Sort with example

In this example, let us write java code for selection sort. Selection sort algorithm is very simple. It is faster for small arrays (i.e. less than 10 to 20 elements) but not efficient on large arrays, as it has **O(n2)** time complexity. The algorithm is as follows.

1. Find the small value in the list

2. Interchange small value with the value in the first position

3. Repeat the steps 1 & 2 for the remaining list (starting from the IInd position and adding 1 each time)

Here is an example sorting five elements

Given Original List : 45 33 56 23 10

Iteration 1 : 33 45 56 23 10, 33 45 56 23 10, 23 45 56 33 10, 10 45 56 33 23

Iteration 2 : 10 45 56 33 23, 10 33 56 45 23, 10 23 56 45 33

Iteration 3 : 10 23 45 56 33 , 10 23 33 56 45

Iteration 4 : 10 23 33 45 56

After sorting the Array:

10 23 33 45 56

The following code snippet accepts number of elements & numbers to be sorted and sorts the given elements using selection sort algorithm.

package net.javaonline; import java.util.Scanner; public class SelectionSort { public static void main(String[] args) { int temp; Scanner sc=new Scanner (System.in); System.out.println("Enter number of elements to be sorted"); int n = sc.nextInt(); int [] numbers=new int[n]; System.out.println("Enter "+n+ " numbers one by one"); for (int i=0 ; i<n; i++) { int number = sc.nextInt(); numbers[i]=number; } System.out.println("Before sorting the Array: "); for (int i=0;i<numbers.length;i++) { System.out.print(numbers[i] +" "); } for (int i=0;i<=numbers.length-1;i++) { for (int j=i+1;j<numbers.length;j++) // loop to find the minimum value { if (numbers[i]>numbers[j] ) // Swap the small number to lowest position { temp=numbers[i]; numbers[i]=numbers[j]; numbers[j]=temp; } } } System.out.println("\nAfter sorting the Array: "); for (int i=0;i<numbers.length;i++) { System.out.print(numbers[i] +" "); } } }

After running the above program :

java SelectionSort

Enter number of elements to be sorted

5

Enter 5 numbers one by one

45

33

56

23

10

Before sorting the Array:

45 33 56 23 10

After sorting the Array:

10 23 33 45 56

## Leave a Reply

You must be logged in to post a comment.