We can sort the array elements by using Selection Sort.We perform a search in array, staring from the first record,to locate the element with the smallest key.When this record is found, we interchange it with the first record in the table.As a result of this interchange,the smallest element is placed in the first position of the table.In the second iteration,we locate second smallest element examining the elements of the table starting from the second position onward We then interchange this element with the second element in the table.We continue this proper of searching for the smallest element in the unsorted position of the table and placing it in its proper place until we have placed all the records in the proper order.The following example shows the above process:
The following programme is the implementation of Selection Sort:
import java.io.*;
class SSort
{
public static void main(String[] args)
{
int temp;
int s=8;
int[] a={45,25,75,15,65,55,95,35};
for(int i=0;i<s;i++)
{
System.out.println("After sorting is "+(i+1)+": ");
for(int k=0;k<s;k++)
System.out.println(a[k]);
for(int j=i+1;j<s;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
}
Output:
After Sorting is 1: 45 25 75 15 65 55 95 35
After Sorting is 2: 15 25 75 45 65 55 95 35
After Sorting is 3: 15 25 75 45 65 55 95 35
After Sorting is 4: 15 25 35 45 65 55 95 75
After Sorting is 5: 15 25 35 45 65 55 95 75
After Sorting is 6: 15 25 35 45 55 65 95 75
After Sorting is 7: 15 25 35 45 55 65 95 75
After Sorting is 8: 15 25 35 45 55 65 75 95
No comments:
Post a Comment