forked from thuva4/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelectionSort.java
More file actions
51 lines (35 loc) · 950 Bytes
/
SelectionSort.java
File metadata and controls
51 lines (35 loc) · 950 Bytes
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
public class SelectionSort {
public static void selectionSort(int[] arr) {
int k, temp, min;
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
min = i;
for (k = i + 1; k < n; k++) {
if (arr[min] > arr[k])
min = k;
}
if (i != min) {
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size: ");
int size = Integer.parseInt(scanner.next());
int[] arr = new int[size];
for(int i=0;i<size;i++) {
System.out.print("Enter the element " + (i+1) + ": ");
arr[i] = Integer.parseInt(scanner.next());
}
selectionSort(arr);
System.out.println("Array after sort:");
System.out.print("[ ");
for(int i=0;i<size;i++)
System.out.print(arr[i] + ((i == size-1) ? "" : ", "));
System.out.println(" ]");
scanner.close();
}
}