Skip to content

Commit 296c3d2

Browse files
authored
Merge pull request thuva4#145 from LegendL3n/master
Implemented SelectionSort of java
2 parents 8c08819 + 2a7f9bc commit 296c3d2

1 file changed

Lines changed: 51 additions & 0 deletions

File tree

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
public class SelectionSort {
2+
3+
public static void selectionSort(int[] arr) {
4+
int k, temp, min;
5+
int n = arr.length;
6+
7+
for (int i = 0; i < n - 1; i++) {
8+
min = i;
9+
10+
for (k = i + 1; k < n; k++) {
11+
if (arr[min] > arr[k])
12+
min = k;
13+
}
14+
15+
if (i != min) {
16+
temp = arr[i];
17+
arr[i] = arr[min];
18+
arr[min] = temp;
19+
}
20+
}
21+
}
22+
23+
public static void main(String[] args) {
24+
Scanner scanner = new Scanner(System.in);
25+
26+
System.out.print("Enter the size: ");
27+
28+
int size = Integer.parseInt(scanner.next());
29+
30+
int[] arr = new int[size];
31+
32+
for(int i=0;i<size;i++) {
33+
System.out.print("Enter the element " + (i+1) + ": ");
34+
35+
arr[i] = Integer.parseInt(scanner.next());
36+
}
37+
38+
selectionSort(arr);
39+
40+
System.out.println("Array after sort:");
41+
42+
System.out.print("[ ");
43+
44+
for(int i=0;i<size;i++)
45+
System.out.print(arr[i] + ((i == size-1) ? "" : ", "));
46+
47+
System.out.println(" ]");
48+
49+
scanner.close();
50+
}
51+
}

0 commit comments

Comments
 (0)