forked from mrizky-kur/Redux-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelectionSort.java
More file actions
94 lines (52 loc) · 1.7 KB
/
SelectionSort.java
File metadata and controls
94 lines (52 loc) · 1.7 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
public class SelectionSortExample {
public static void selectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++){
if (arr[j] < arr[index]){
index = j;//searching for lowest index
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}
public static void main(String a[]){
int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
System.out.println();
selectionSort(arr1);//sorting array using selection sort
System.out.println("After Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
}
}
import java.util.Arrays;
public class SelectionSort {
public static void main(String[] args) {
int[] arr = { 1, 4, 56, 3, 2, 7, 9 };
Selection(arr, arr.length - 1, 0, 0);
System.out.println(Arrays.toString(arr));
}
static void Selection(int[] arr, int r, int c, int max) {
if (r == 0)
return;
if (r > c) {
if (arr[c] > arr[max]) {
Selection(arr, r, c + 1, c);
} else
Selection(arr, r, c + 1, max);
} else {
int t = arr[max];
arr[max] = arr[r - 1];
arr[r - 1] = t;
Selection(arr, r - 1, 0, 0);
}
}
}