Selection Sort program in Java

Selection Sort:

Selection sort is easy and well known sorting technique.In selection sort unordered list is divided into two parts sorted and unsorted. minimum number from unsorted list is selected and placed in at sorted array at proper location.this process is done until list get sorted.

Worst case performance:     О(n2)
Best case performance:         Ðž(n2)
Average case performance: О(n2)

import java.io.*;
class sort
{

static void selection(int c[],int n)
{
int i,indx,j,large,z=1;
for(i=n-1;i>0;i--)
{
large=c[0];
indx=0;
for(j=1;j<=i;j++)
if(c[j]>large)
{
large=c[j];
indx=j;
}
c[indx]=c[i];
c[i]=large;
System.out.print("PASS "+(z++)+":");
for(int v=0;v<n;v++)
System.out.print("\t"+c[v]);
System.out.println();
}
System.out.println("\nSorted Elements are :");
for(i=0;i<n;i++)
System.out.print("\t"+c[i]);
System.out.println();
}
}

class Selection_sort

{
public static void main(String args[ ])throws IOException
{
int i,n=0;

DataInputStream in = new DataInputStream(System.in);
System.out.print("Enter how many numbers to be sorted : ");
n = Integer.parseInt(in.readLine());
int x1[]=new int[n];
int x3[]=new int[n];
int x2[]=new int[n];
System.out.println("Enter numbers");
for(i=0;i<n;i++)
{
x1[i]=x2[i]=x3[i]= Integer.parseInt(in.readLine());
}
System.out.println();
sort s=new sort();

System.out.println("SORTING BY SELECTION SORT");
s.selection(x2,n);

}
}
/*OUTPUT:
Enter how many numbers to be sorted : 5
Enter numbers
65
45
60
33
15

SORTING BY SELECTION SORT
PASS 1: 15 45 60 33 65
PASS 2: 15 45 33 60 65
PASS 3: 15 33 45 60 65
PASS 4: 15 33 45 60 65

Sorted Elements are :
15 33 45 60 65

*/

Selection Sort in C

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *