Best Way To Implement Selection Sort In Java

Sharing is healthy !!

This post explains the best way to implement selection sort in java.

what is selection sort?

Selection sort is an (sorting)algorithm. It is considered as one of the simplest algorithms.

In this sorting algorithm, unsorted(lowest) element is shifted to its correct position in an array.

The loop continues until the arrangement of integer elements in array is in the ascending order.

The number of times the sorting takes place will always be one less than the number of integer elements in an array.

Best Way To Implement Selection Sort In Java

example: Best Way To Implement Selection Sort In Java

Also Read – Insertion Sort In Java

import java.util.Scanner;

public class Selection_Sort_In_Java {
 
public static void to_Sort(int[] array){
 
int S = array.length;
int a;
int b;
int place;
int temp;
 
for(a = 0;a < S - 1;a++)
{
place = a;
for(b = a + 1;b < S;b++){
if(array[b] < array[place]){
place = b;
}
}
 
temp = array[a];
array[a] = array[place];
array[place] = temp;
}
}

public static void main(String[] args) {
 
Scanner sc = new Scanner(System.in);
System.out.println("Best Way To Implement Selection Sort In Java");
int x;
int y;
 
// accepting user entered integer elements
System.out.println("Please enter number of integer elements");
x = sc.nextInt();
 
// creating integer array elements
int[] arr = new int[x];
 
System.out.println("Please enter " + x + " integer elements.");
System.out.println("Integer elements before sorting: ");
for(y = 0;y < x;y++)
arr[y] = sc.nextInt();
 
// calling to_Sort method
to_Sort(arr);
 
// Displaying sorted array
System.out.println("Integer elements after sorting: ");
for(y = 0;y < x;y++)
System.out.print(arr[y] + " ");
System.out.println();

}

}

Output:

Best Way To Implement Selection Sort In Java
Please enter number of integer elements: 5
Please enter 5 integer elements.
Integer elements before sorting: 5 4 -3 2 -1
Integer elements after sorting: -3 -1 2 4 5

Sharing is healthy !!

Leave a Reply

Your email address will not be published.