-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelectionSort.java
More file actions
40 lines (32 loc) · 931 Bytes
/
Copy pathSelectionSort.java
File metadata and controls
40 lines (32 loc) · 931 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
package com.sorting;
import java.util.Arrays;
public class SelectionSort {
public static void main(String[] args) {
int[] arr = {4, 2, 1, 5};
selectionSort(arr);
System.out.println(Arrays.toString(arr));
}
static void selectionSort(int[] arr){
for(int i=0; i<arr.length; i++){
int last = arr.length - i - 1;
int maxIndex = findMax(0, last, arr);
swap(maxIndex, last, arr);
}
}
static void swap(int maxIndex, int last, int[] arr){
int temp = arr[maxIndex];
arr[maxIndex] = arr[last];
arr[last] = temp;
}
static int findMax(int start, int last, int[] arr) {
int max = arr[start];
int maxIndex = 0;
for(int i=1; i<=last; i++){
if(arr[i] > max){
max = arr[i];
maxIndex = i;
}
}
return maxIndex;
}
}