Skip to content

Commit 0e8463c

Browse files
Selection Sort in Java
1 parent cb26595 commit 0e8463c

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

sorting/SelectionSort.java

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*
2+
Copyright (C) Deepali Srivastava - All Rights Reserved
3+
This code is part of DSA course available on CourseGalaxy.com
4+
*/
5+
6+
import java.util.Scanner;
7+
8+
public class SelectionSort
9+
{
10+
private SelectionSort(){} //this class is not for instantiation
11+
12+
public static void sort(int[] a, int n)
13+
{
14+
int minIndex,temp,i,j;
15+
16+
for(i=0; i<n-1; i++)
17+
{
18+
minIndex=i;
19+
for(j=i+1; j<n; j++)
20+
{
21+
if(a[j]<a[minIndex])
22+
minIndex=j;
23+
}
24+
if(i!=minIndex)
25+
{
26+
temp = a[i];
27+
a[i] = a[minIndex];
28+
a[minIndex] = temp;
29+
}
30+
}
31+
}
32+
33+
public static void main(String[] args)
34+
{
35+
int i,n;
36+
int[] a = new int[20];
37+
Scanner scan = new Scanner(System.in);
38+
39+
System.out.print("Enter the number of elements : ");
40+
n = scan.nextInt();
41+
42+
for(i=0; i<n; i++)
43+
{
44+
System.out.print("Enter element " + (i+1) + " : ");
45+
a[i] = scan.nextInt();
46+
}
47+
48+
sort(a,n);
49+
50+
System.out.println("Sorted array is : ");
51+
for(i=0; i<n; i++)
52+
System.out.print(a[i] + " ");
53+
System.out.println();
54+
scan.close();
55+
}
56+
}

0 commit comments

Comments
 (0)