Selection Sort Implementation In JAVA
Sorting Techniques
import java.io.DataInputStream;
class SelectionSortImpl
{
private static void swap(int data[], int left, int right)
{
int temp = data[left];
data[left] = data[right];
data[right] = temp;
}
public static void Sort(int data[], int n)
{
int num = n;
int i;
int max;
while(num >0)
{
max=0;
for(i=1;i<num;i++)
{
if(data[max]<data[i])
max=i;
}
swap(data,max,num-1);
num--;
}
}
}
public class SelectionSort {
public static void main(String args[])
{
DataInputStream in = new DataInputStream(System.in);
System.out.println("Enter the array to be sorted");
int data[]=new int[10];
try
{
for(int i=0;i<10;i++)
data[i]=Integer.parseInt(in.readLine());
}
catch(Exception e) {}
SelectionSortImpl.Sort(data, 10);
System.out.println("Sorted array:");
for(int i=0;i<10;i++)
System.out.println(+data[i]);
}
}
-----------------------Output-------------------------------------------------
--------------------------------------------------------------------------------
Enter the array to be sorted
45
12
78
1
7
14
90
27
9
47
Sorted array:
1
7
9
12
14
27
45
47
78
90
class SelectionSortImpl
{
private static void swap(int data[], int left, int right)
{
int temp = data[left];
data[left] = data[right];
data[right] = temp;
}
public static void Sort(int data[], int n)
{
int num = n;
int i;
int max;
while(num >0)
{
max=0;
for(i=1;i<num;i++)
{
if(data[max]<data[i])
max=i;
}
swap(data,max,num-1);
num--;
}
}
}
public class SelectionSort {
public static void main(String args[])
{
DataInputStream in = new DataInputStream(System.in);
System.out.println("Enter the array to be sorted");
int data[]=new int[10];
try
{
for(int i=0;i<10;i++)
data[i]=Integer.parseInt(in.readLine());
}
catch(Exception e) {}
SelectionSortImpl.Sort(data, 10);
System.out.println("Sorted array:");
for(int i=0;i<10;i++)
System.out.println(+data[i]);
}
}
-----------------------Output-------------------------------------------------
--------------------------------------------------------------------------------
Enter the array to be sorted
45
12
78
1
7
14
90
27
9
47
Sorted array:
1
7
9
12
14
27
45
47
78
90
You Might Also Like :