# Selection sort in java

Selection sort is a one of the most important sorting technique in the data structure. It is very easily used sorting algorithm .

In the Selection sort algorithm, first we have to find the smallest element of an array and after than we need to swap the first and the the shortest element of an array.,this process will be going on up to we will not get the complete sorting array.

Example:Let's discuss the Selection Sort algorithm with the help of a java program.

import java.util.Scanner;

class Selection

{

static int n;

static int[] arr;

public static void getData()

{

System.out.println("Enter size of an array");

Scanner sc = new Scanner(System.in);

n=sc.nextInt();

arr=new int[n];

System.out.println(" Enter Array elements:");

for(int i=0;i<n;i++)

{

System.out.println("Array elements are:"+(i+1));

arr[i]=sc.nextInt();

}

}

public static void selectionSort(int[] arr)

{

int min,temp=0;

for(int i=0;i<n;i++)

{

min=i;

for(int j=i+1;j<n;j++)

{

if(arr[j]<arr[min])

{

min=j;

}

}

temp=arr[i];

arr[i]=arr[min];

arr[min]=temp;

}

}

public static void main(String[] args)

{

getData();

System.out.println("elements before sorting:");

for(int i=0;i<arr.length;i++)

{

System.out.print(arr[i]+" ");

}

selectionSort(arr);

System.out.println("");

System.out.println("elements after sorting:");

for(int i=0;i<Selection.arr.length;i++)

{

System.out.print(arr[i]+" ");

}

}

}

output:

Enter size of an array

5

Enter Array elements:

Array elements are:1

50

Array elements are:2

10

Array elements are:3

23

Array elements are:4

6

Array elements are:5

1

elements before sorting:

50 10 23 6 1

elements after sorting:

1 6 10 23 50

Description:

This is the complete flow of the program through code only we can solve the selection sort algorithm without any problem

public static void selectionSort(int[] arr)

{

int min,temp=0;

for(int i=0;i<n;i++)

{

min=i;

for(int j=i+1;j<n;j++)

{

if(arr[j]<arr[min])

{

min=j;

}

}

temp=arr[i];

arr[i]=arr[min];

arr[min]=temp;

}

}

## No comments:

## Post a Comment