Java Source Code: Sort Numbers in Selection Sort
By aisha91
Below is the sample java source code on sorting numbers using selection sort. Selection Sort in java is much prepared by the programmers when it comes on sorting. Here, I will present to you on how the selection sort works.
How Selection Sort works in Java?
Assuming the user entered 6 numbers which are:
4 5 1 3 2 6
The program will sort it in an ascending order using selection sort. The program will simply compare the first number which is 4 to the second number, third number and so on, and then sort. See below on how it works.
From the entered numbers 4 5 1 3 2 6
Sorted To:
5 1 3 2 4 6
1 3 2 4 5 6
1 2 3 4 5 6 //sorting ends here and this will be output to the screen.
Sorting in selection sort is pretty fast than bubble sort. But If you are interested on comparing other methods of sorting like bubble sort , you can visit the link below.
Below is the java source code for Selection Sort.
Java Source Code: How to Sort Numbers using Selection Sort
//java class
public class SelectionSort
{
public void SelectionSort(int[] arr){
for(int i=0; i<arr.length; i++)
{
for(int j=i+1; j<arr.length; j++)
{
if(arr[i] > arr[j] )
{
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
for(int i=0; i<arr.length; i++)
{
System.out.print(arr[i] + " ");
}
}
//main class
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int n = input.nextInt();
int[] x = new int[n];
System.out.print("Enter "+ n +" numbers: ");
for(int i=0; i<n; i++)
{
x[i] = input.nextInt();
}
SelectionSort access = new SelectionSort();
System.out.print("The Sorted numbers: ");
access.SelectionSort(x);
}
}
Sample Output:
Enter the size of the array: 10
Enter 10 numbers: 500 600 250 1000 35 50 10 15 20 1
The Sorted numbers: 1 10 15 20 35 50 250 500 600 1000
Want more Java Source codes? Choose source codes below.
- Java Source Code: Sort Numbers in Bubble Sort
- Java Simple Codes for Beginners
- A Java source code: How to Output Asterisk in Different Forms Using Recursion
- Java Source Code: A Recursive Asterisk Diamond Shape
- Java Source code on Printing the Greatest Common Divisor (GCD) using Recursion
- Java Source code: How to Print a String Backward using Recursion
- Java Source code: How to Add Numbers inside an Array using For Loop
- Java Source code: How to Add numbers inside an Array Using Recursion
- Java Source Code on a Recursive Linear Search
- Java Source Code: Binary Search in Recursion
- Java source code: How to Output the Answer of the Integer X to the Power Y
- Java Source Code: How to make a Program that will determine a Person's Salutation and Current Age
- Java Source Code: Recursive Snow Flakes
Perhaps, these following hubs would be useful to you.




web-tools 3 months ago
good.