forked from tornado-12/learn-to-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelectionSort.java
More file actions
51 lines (47 loc) · 1.4 KB
/
SelectionSort.java
File metadata and controls
51 lines (47 loc) · 1.4 KB
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
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class SelectionSort {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the size of array");
int t = Integer.parseInt(br.readLine());
int[] arr = new int[t];
System.out.println("Enter the elements of array with space seperation");
String[] s = br.readLine().trim().split(" ");
int i=0;
for(String c: s){
arr[i] = Integer.parseInt(c);
i++;
}
selectionSort(arr);
System.out.println("Output after Sorting");
for(int k: arr){
System.out.print(k+" ");
}
}
private static void selectionSort(int[] a) {
int n = a.length;
// if size is zero or 1 array is already sorted.
if(n==0||n==1) return;
for(int i=0;i<n;i++)
{
int min=a[i];
int t=i;
// traverse the array and find mininum element!
for(int j=i+1;j<n;j++)
{
if(min>a[j])
{
min=a[j];
t=j;
}
}
// swap with the minimum
if(t!=i)
{
a[t]=a[i];
a[i]=min;
}
}
}
}