-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelectionSort.java
More file actions
41 lines (37 loc) · 1.1 KB
/
SelectionSort.java
File metadata and controls
41 lines (37 loc) · 1.1 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
38
39
40
41
class SelectionSort {
static void selectionSort(int arr[]){
for(int i = 0; i < arr.length-1; i++){
int minPos = i;
boolean swaps = false;
for(int j = i+1; j < arr.length; j++){
if(arr[j] < arr[minPos]){
minPos = j;
}
}
//swapping minimum element to starting index of array
if(minPos != i){
int temp = arr[minPos];
arr[minPos] = arr[i];
arr[i] = temp;
swaps = true;
}
//checking if no swaps happens in 1st pass
if(!swaps){
break;
}
}
}
public static void main(String[] args) {
int arr[] = {5,3,4,2,1};
System.out.println("Array before sorting : ");
for(int val : arr){
System.out.print(val + " ");
}
System.out.println();
selectionSort(arr);
System.out.println("Array aftr sorting : ");
for(int val : arr){
System.out.print(val + " ");
}
}
}