forked from Annex5061/java-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathselection-sort.java
42 lines (36 loc) · 1.08 KB
/
selection-sort.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
// SelectionSort
import java.util.*;
public class SelectionSort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter length");
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
selection(arr);
System.out.println(Arrays.toString(arr));
}
static void selection(int[] arr) {
for(int i = 0; i < arr.length; ++i) {
int last = arr.length - i - 1;
int maxIndex = getMaxIndex(arr, 0, last);
swap(arr, maxIndex, last);
}
}
static void swap(int[] arr, int first, int second) {
int temp = arr[first];
arr[first] = arr[second];
arr[second] = temp;
}
static int getMaxIndex(int[] arr, int start, int end) {
int max = start;
for(int i = start; i <= end; ++i) {
if (arr[max] < arr[i]) {
max = i;
}
}
return max;
}
}