forked from Ritikraja07/Java-problem-Open-Source
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselectionSort.java
34 lines (30 loc) · 914 Bytes
/
selectionSort.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
import java.util.Arrays;
public class selectionSort {
public static void main(String[] args) {
int []arr={4,1,3,9,7};
selectionArr(arr);
System.out.println(Arrays.toString(arr));
}
static void selectionArr(int[]arr){
for (int i = 0; i < arr.length; i++) {
//find the max item in the remaining array and swap it with correct index
int last=arr.length-i-1;
int maxInd=getMaxInd(arr,0,last);
swap(arr, maxInd, last);
}
}
static int getMaxInd(int[]arr,int start,int last){
int max=start;
for (int i = start; i<=last; i++) {
if(arr[max]<arr[i]){
max=i;
}
}
return max;
}
static void swap(int[]arr,int first,int second){
int temp=arr[first];
arr[first]=arr[second];
arr[second]=temp;
}
}