Selection Sort Program in Java Example

Selection sort in java program. In Java programming, there is a selection sort program. This selection sort program is a very advanced sorting program that is also very relevant. It will choose the item and sort the elements.

Sorting Algorithm in Java

The unsorted array’s smallest element is chosen and swapped with the leftmost element, resulting in that element becoming a part of the sorted array. The unsorted array border is moved from one element to the right in this operation. 

The unsorted array’s smallest element is chosen and swapped with the leftmost element, resulting in that element becoming a part of the sorted array. The unsorted array border is moved from one element to the right in this operation.

Array in Java Program

In Java, an array is a collection of variables that are referred to by a single variable name and an index number. An array’s items are called elements. An array’s items must all be of the same type. A data structure that contains a group of elements is known as an array. These items are often all of the same data type, such as an integer or a string.

If Else Statement to Execute Selection Sort in Java

The simplest basic decision-making statement in Java is the if statement. It is used to determine if a statement or a block of statements will be executed or not, that is if a condition is true, a block of statements will be executed; otherwise, it will not. In Java, the if statement is used to execute a block of code if a condition is true. If a condition evaluates to false, the if…else statement is used alongside an if statement to run code. The if…else…if statement is also used to test multiple conditions.

public class Main
{ 
public static void sorting(int[] arr)
{ 
for (int i = 0; i < arr.length - 1; i++) 
{ 
int index = i; 
for (int j = i + 1; j < arr.length; j++)
{ 
if (arr[j] < arr[index])
{ 
index = j;
} 
} 
int small = arr[index]; 
arr[index] = arr[i]; 
arr[i] = small; 
} 
} 
public static void main(String a[])
{ 
int[] arr1 = {45,56,67,1,34,46,67}; 
System.out.println("Before Selection sort"); 
for(int i:arr1){ 
System.out.print(i+" "); 
} 
System.out.println(); 
sorting(arr1);
System.out.println("After Selection sort"); 
for(int i:arr1){ 
System.out.print(i+" "); 
} 
} 
} 

Output:

Before Selection sort
45 56 67 1 34 46 67
After Selection sort
1 34 45 46 56 67 67