0% found this document useful (0 votes)
6 views2 pages

Selection Sort

The document contains a Java program that implements the Selection Sort algorithm to arrange N values in an array in ascending order. It includes methods for accepting input, finding the lowest value, performing the sort, and displaying the sorted array. The program is structured with a main method that orchestrates the execution of these functionalities.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Selection Sort

The document contains a Java program that implements the Selection Sort algorithm to arrange N values in an array in ascending order. It includes methods for accepting input, finding the lowest value, performing the sort, and displaying the sorted array. The program is structured with a main method that orchestrates the execution of these functionalities.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Class SelectionSort 1/2

1 /**Program to store N values into an array, arrange them in ascending ord


er
2 * using Selection sort technique.
3 **/
4 import java.util.*;
5 class SelectionSort
6 {
7 int a[];
8

9 void accept()
10 {
11 Scanner scan = new Scanner(System.in);
12 System.out.println("Enter the size of the array");
13 int n = scan.nextInt();
14 a = new int[n];
15 System.out.println("Enter the values ");
16 for(int i=0;i<a.length;i++)
17 {
18 a[i] = scan.nextInt();
19 }
20 }
21

22 int lowest(int s) // function to select the lowest value from the s


tarting index s
23 { // and returns the index of the lowest value.
24 int low=a[s],pos=s;
25 for(int i=s+1;i<a.length;i++)
26 {
27 if(a[i]<low)
28 {
29 low=a[i];
30 pos=i;
31 }
32 }
33 return pos;
34 }
35

36 void selectionSort()
37 {
38 int i,j,t,len=a.length-1;
39 for(i=0;i<len;i++)
40 {
41 int k = lowest(i); // calling the function lowest by passing
starting index of the array.
42 if(a[k]<a[i])
43 {
44 t=a[i]; // swapping the value with lowest value
45 a[i]=a[k];
46 a[k]=t;

Nov 22, 2024 10:29:32 AM


Class SelectionSort (continued) 2/2

47 }
48 }
49 }
50

51 void display()
52 {
53 for(int i=0;i<a.length;i++)
54 {
55 System.out.println(a[i]);
56 }
57 }
58

59 static void main()


60 {
61 SelectionSort obj = new SelectionSort();
62 obj.accept();
63 obj.selectionSort();
64 obj.display();
65 }
66 }
67

Nov 22, 2024 10:29:32 AM

You might also like