About Me

My photo
Vijayapur, Karnataka, India
I am interested in Teaching.

Monday, 19 June 2023

Selection Sort program in Java

Filename : SelectionSort.java

 class SelectionSort

{
// Selection Sort Method
void 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 array
void printarrayay(int array[])
{
int n = array.length;
for (int i=0; i<n; ++i)
System.out.print(array[i]+" ");
System.out.println();
}
// Main Method
public 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 array
10 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:

Quiz-1 for DCET 2025 (Introduction to Python)

 1. Introduction to Python https://docs.google.com/forms/d/e/1FAIpQLSc3LFrMaswLg6mltJ3NN5QGbALA9Uc53KWPp4oV5HN4SaM0Iw/viewform?usp=sharing...