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