Filename : SelectionSort.java
class SelectionSort
{// Selection Sort Methodvoid sort(int array[]){int n = array.length;for (int i = 0; i < n-1; i++){int min_element = i;for (int j = i+1; j < n; j++)if (array[j] < array[min_element])min_element = j;int temp = array[min_element];array[min_element] = array[i];array[i] = temp;}}// Method to print the elements of an arrayvoid printarrayay(int array[]){int n = array.length;for (int i=0; i<n; ++i)System.out.print(array[i]+" ");System.out.println();}// Main Methodpublic static void main(String args[]){SelectionSort ob = new SelectionSort();int array[] = {15, 10, 99, 53, 36};ob.sort(array);System.out.println("Sorted array");ob.printarrayay(array);}}
How to compile?
javac SelectionSort.java
How to run?
java SelectionSort
Output:
Sorted array10 15 36 53 99
/* Java code for the implementation of selection sort technique
for the random numbers generated for larger value of n to calculate its time complexity,
Programmer: Miss. Sindhu Badiger, Date: 27-07-2023 in DAA Lab, BLDEACET, Vijayapur.
*/
import java.util.*;
public class selectionsort {
public static void main(String args[])
{
Scanner SC=new Scanner(System.in);
Random randomGenerator=new Random();
int n, i, j, temp;
System.out.println("Enter Array size:"); n=SC.nextInt();
int a[]=new int[n];
for(i=0;i<n;i++)
{
a[i]=randomGenerator.nextInt(n);
System.out.println("Number:"+a[i]);
}
System.out.println("Sorting array elements using Selection sort technique");
long startTime=System.nanoTime();
for(i=0;i<n;i++)
{
int min=i;
for(j=i+1;j<n;j++)
{
if(a[j]<a[min])
{
temp=a[min];
a[min]=a[j];
a[j]=temp;
}
}
}
long endTime=System.nanoTime();
System.out.println("Now the array after sorting is:\n");
for(i=0;i<n;i++)
{
System.out.println(a[i]+ "\n");
}
long elapseTime=(endTime-startTime);
System.out.println("Time taaken to sort is:"+elapseTime);
}
}

No comments:
Post a Comment