Selection Sort
Write a program to sort an array using Selection Sort technique. In this technique, smallest/greatest element is searched and is swapped by the leftmost element of the array repeatedly to arrange the array in sorted order.
import java.util.*;
class SelectionSort{
public static void main(String args[])throws InputMismatchException{
Scanner scan = new Scanner(System.in);
int n,i,j,s,p,t;
System.out.println("Enter the number of elements : ");
n = scan.nextInt();
int a[] = new int[n]; //declare array
System.out.println("Enter " + n + " elements.");
for(i = 0; i < n; i++)
a[i] = scan.nextInt();
//sort the array in ascending order
for(i = 0; i < n; i++){
s = a[i];
p = i;
for(j = i+1; j < n; j++){
if(s > a[j]){
s = a[j];
p = j;
}//end of if
}//end of inner loop
//sort the leftmost element with the smallest element
t = a[i];
a[i] = a[p];
a[p] = t;
}//end of outer loop
//display the sorted array
for(i = 0; i < n; i++){
System.out.println(a[i] + " ");
}//end of loop
}//end of main
}//end of class
Have something to say? Log in to comment on this post.
0 comments