QUESTION:
Write a program to perform Selection Sort for an integer array in Java, BlueJ.
Write a program to perform Selection Sort for an integer array in Java, BlueJ.
CODE:
import java.io.*;
public class SelectionSort
{
public static int[] sort(int arr[])
{
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
{
if (arr[j] < arr[index])
{
index = j;
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
return arr;
}
public static void main()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int num;
System.out.println("Enter the number of elements to be sorted: ");
num=Integer.parseInt(br.readLine());
int arr1[]=new int[num];
System.out.println("Enter the array to be sorted: ");
for(int i=0;i<arr1.length;i++)
arr1[i]=Integer.parseInt(br.readLine());
int[] arr2 = sort(arr1);
System.out.println("\nThe elements of the sorted array: ");
for(int i:arr2)
{
System.out.print(i+"\t");
}
}
}
No comments:
Post a Comment