0% found this document useful (0 votes)
5 views

Selection Sort

Selection sort

Uploaded by

jones.codyxxx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Selection Sort

Selection sort

Uploaded by

jones.codyxxx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

ASSIGNMENT 2: 15/4/24

Design a class "Selection sort" that inputs array from the user and sort it in ascending order using
selection sort technique. A class is declared to give details of the constructor and member methods.
Data member:
int ar - Integer array to store array numbers.
int n - To store the length of the array.
Member methods:
Selection_Sort - Constructor to initialize n to O.
void readlist() - To accept value of n and array elements from user.
int Index_Of_Min(int startindex) - Return the index position of the smallest value.
void sort() - To sort the array in ascending order using selection sort technique.
void display() - To display the sorted array.

import java.util.*;
class Selection_Sort_Diganta_Biswas
{ //start of class
int ar[], n; //declaration of variables
Selection_Sort_ Diganta_Biswas ()
{
n = 0; //initialising variable
}
void readlist()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of array");
n = sc.nextInt(); //Entering size of the array
ar = new int[n];
System.out.println("Enter array elements");
for (int i = 0; i < n; i++)
{
ar[i] = sc.nextInt(); //Entering array elements
}
}
int Index_Of_Min(int startindex)
{
int p = startindex;
for (int j = p + 1; j < n; j++)
{
if (ar[j] < ar[p])
p = j;
}
return p;
}
void sort()
{ //Selection sorting in ascending order
for (int i = 0; i < n; i++)
{
int x = Index_Of_Min(i);
int t = ar[i];
ar[i] = ar[x];
ar[x] = t;
}
}
void display()
{
System.out.println("The sorted array is: ");
for (int i = 0; i < n; i++)
{
System.out.print(ar[i] + " "); //displaying the sorted array
}
}
public static void main()
{ //start of main
Selection_Sort_ Diganta_Biswas ob = new Selection_Sort_ Diganta_Biswas ();
ob.readlist();
ob.sort();
ob.display();
} //end of main
} //end of class

//OUTPUT
//Enter the size of array
//3
//Enter array elements
//45
//89
//12
//The sorted array is:
//12 45 89

Variable Description:-
Name Datatype Purpose
ar int array to sort
n int size of array
i int loop variable
j int loop variable
p int counter variable
t int temporary variable

You might also like