forked from hariom20singh/foodewbpage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SelectionSort.java
49 lines (43 loc) · 1.25 KB
/
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.util.*;
//Problem : Selection Sort
public class SelectionSort {
public static void selectionSort(int arr[]) {
for(int turn=0; turn<arr.length; turn++) {
int minPos = turn;
for(int j=turn+1; j<arr.length; j++) {
if(arr[minPos] > arr[j]) {
minPos = j;
}
}
//swap
int temp = arr[turn];
arr[turn] = arr[minPos];
arr[minPos] = temp;
}
}
public static void selectionSortDescending(int arr[]) {
for(int turn=0; turn<arr.length; turn++) {
int minPos = turn;
for(int j=turn+1; j<arr.length; j++) {
if(arr[minPos] < arr[j]) {
minPos = j;
}
}
//swap
int temp = arr[turn];
arr[turn] = arr[minPos];
arr[minPos] = temp;
}
}
public static void printArr(int arr[]) {
for(int i=0; i<arr.length; i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
}
public static void main(String args[]) {
int arr[] = {5, 4, 1, 3, 2};
selectionSortDescending(arr);
printArr(arr);
}
}