codescracker


java

Java Program Selection Sort



« Previous Program Next Program »


Selection Sort

To sort an array in ascending order using the selection sort technique in Java programming, you have to ask to the user to enter the array elements or number, now start comparing the array elements, on found, start swapping with the variable temp, place the first number in the temp and the second number in the first, and then temp in the second number and continue for the next match to sort the whole array in ascending order.

Java Programming Code for Selection Sort

Following Java Program ask to the user to enter the array size and array element, then it will sort the array is ascending order and display the sorted array:

/* Java Program Example - Selection Sort */
		
import java.util.Scanner;

public class JavaProgram
{
   public static void main(String args[])
   {
       int size, i, j, temp;
       int arr[] = new int[50];
       Scanner scan = new Scanner(System.in);
	   
       System.out.print("Enter Array Size : ");
       size = scan.nextInt();
	   
       System.out.print("Enter Array Elements : ");
       for(i=0; i<size; i++)
       {
           arr[i] = scan.nextInt();
       }
	   
       System.out.print("Sorting Array using Selection Sort Technique..\n");
       for(i=0; i<size; i++)
       {
           for(j=i+1; j<size; j++)
           {
               if(arr[i] > arr[j])
               {
                   temp = arr[i];
                   arr[i] = arr[j];
                   arr[j] = temp;
               }
           }
       }
	   
       System.out.print("Now the Array after Sorting is :\n");
       for(i=0; i<size; i++)
       {
           System.out.print(arr[i]+ "  ");
       }
   }
}

When the above Java Program is compile and executed, it will produce the following output:

selection sort in Java Programming

Same Program in Other Languages

You may also like to learn and practice the same program in other popular programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test