Skip to content

Commit 7c76549

Browse files
Merge pull request #33 from HetuKariya/SelectionSort
Added SelectionSort.java Please add Hactoberfest Accepted tag and merge it
2 parents fa4f4c0 + 37ef78c commit 7c76549

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

java/SelectionSort.java

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import java.util.*;
2+
3+
public class SelectionSort {
4+
public static void main(String[] args) {
5+
Scanner scan = new Scanner(System.in);
6+
int n = scan.nextInt();
7+
int[] arr = new int[n];
8+
for(int i = 0; i < n; i++)
9+
arr[i] = scan.nextInt();
10+
selectionSort(arr);
11+
System.out.println(Arrays.toString(arr));
12+
}
13+
14+
public static void selectionSort(int[] arr) {
15+
for(int i = 0; i < arr.length; i++) {
16+
// find the max item in the remaining array and swap with the correct index
17+
int last = arr.length - i - 1;
18+
int maxIndex = getMaxIndex(arr, 0, last);
19+
swap(arr, maxIndex, last);
20+
}
21+
}
22+
23+
public static int getMaxIndex(int[] arr, int start, int end) {
24+
int max = start;
25+
for(int i = start; i <= end; i++) {
26+
if(arr[i] > arr[max])
27+
max = i;
28+
}
29+
return max;
30+
}
31+
32+
public static void swap(int[] arr, int i, int correct) {
33+
int temp = arr[i];
34+
arr[i] = arr[correct];
35+
arr[correct] = temp;
36+
}
37+
}

0 commit comments

Comments
 (0)