Tuesday, November 9, 2010

Selection sort using java

Working :

This sorting technique requires n-1 passes to sort an array of n integers. In pass number i, we select minimum element from a[i] to a[n-1] and then swap this minimum element with a[i].

Code :


import java.util.*;

public class Selection
{
static void selectionsort(int a[])
{
int min,p,t;

for(int i=0;i<=a.length-2;i++)
{
min = a[i];p=i;

for(int j=i+1;j<=a.length-1;j++)
if(a[j] < min)
{
min = a[j];
p = j;
}

//swap a[i] and a[p]

t = a[i];
a[i] = a[p];
a[p] = t;

}//end of for i loop
}//end of selectionsort

public static void main(String args[])
{
System.out.println("Enter number of elements you wish to sort : ");
Scanner sc = new Scanner(System.in);

int n = sc.nextInt();

//declare array of n elements

int a[] = new int[n];
//scan array from 0 to n-1 locations
for(int i = 0; i <= n-1;i++)
{
System.out.print("\nEnter element " + (i+1) + " : ");
a[i] = sc.nextInt();
}

System.out.println("\nOriginal array : ");

for(int i=0;i<=n-1;i++)
System.out.print(a[i] + " ");

//sort the array

selectionsort(a);

//print sorted array

System.out.println("\nSorted array : ");

for(int i=0;i<=n-1;i++)
System.out.print(a[i] + " ");

}

}


Output :


Enter number of elements you wish to sort :
5

Enter element 1 : 5

Enter element 2 : 4

Enter element 3 : 1

Enter element 4 : 2

Enter element 5 : 6

Original array :
5 4 1 2 6
Sorted array :
1 2 4 5 6

0 comments:

Post a Comment