forked from dimpeshmalviya/JavaBasicPrograms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelectionSort.java
More file actions
37 lines (33 loc) · 1.06 KB
/
SelectionSort.java
File metadata and controls
37 lines (33 loc) · 1.06 KB
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
import java.util.*;
public class SelectionSort {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] arr = new int[n];
for(int i = 0; i < n; i++)
arr[i] = scan.nextInt();
selectionSort(arr);
System.out.println(Arrays.toString(arr));
}
public static void selectionSort(int[] arr) {
for(int i = 0; i < arr.length; i++) {
// find the max item in the remaining array and swap with the correct index
int last = arr.length - i - 1;
int maxIndex = getMaxIndex(arr, 0, last);
swap(arr, maxIndex, last);
}
}
public static int getMaxIndex(int[] arr, int start, int end) {
int max = start;
for(int i = start; i <= end; i++) {
if(arr[i] > arr[max])
max = i;
}
return max;
}
public static void swap(int[] arr, int i, int correct) {
int temp = arr[i];
arr[i] = arr[correct];
arr[correct] = temp;
}
}