FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Java/Sorts/SelectionSort.java at master · comelf/Java · GitHub
comelf
/
Java
Public
forked from
TheAlgorithms/Java
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
Java
/
Sorts
/
SelectionSort.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
71 lines (56 loc) · 1.77 KB
Breadcrumbs
Java
/
Sorts
/
SelectionSort.java
Copy path
File metadata and controls
71 lines (56 loc) · 1.77 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package
Sorts
;
/**
* @author Varun Upadhyay (https://github.com/varunu28)
* @author Podshivalov Nikita (https://github.com/nikitap492)
* @see SortAlgorithm
*/
public
class
SelectionSort
implements
SortAlgorithm
{
/**
* This method swaps the two elements in the array
* @param <T>
* @param arr, i, j The array for the swap and
the indexes of the to-swap elements
*/
public
<
T
>
void
swap
(
T
[]
arr
,
int
i
,
int
j
) {
T
temp
=
arr
[
i
];
arr
[
i
] =
arr
[
j
];
arr
[
j
] =
temp
;
}
/**
* This method implements the Generic Selection Sort
*
* @param arr The array to be sorted
* Sorts the array in increasing order
**/
@
Override
public
<
T
extends
Comparable
<
T
>>
T
[]
sort
(
T
[]
arr
) {
int
n
=
arr
.
length
;
for
(
int
i
=
0
;
i
<
n
-
1
;
i
++) {
// Initial index of min
int
min
=
i
;
for
(
int
j
=
i
+
1
;
j
<
n
;
j
++) {
if
(
arr
[
min
].
compareTo
(
arr
[
j
]) <
0
) {
min
=
j
;
}
}
// Swapping if index of min is changed
if
(
min
!=
i
) {
swap
(
arr
,
i
,
min
);
}
}
return
arr
;
}
// Driver Program
public
static
void
main
(
String
[]
args
) {
Integer
[]
arr
= {
4
,
23
,
6
,
78
,
1
,
54
,
231
,
9
,
12
};
SelectionSort
selectionSort
=
new
SelectionSort
();
Integer
[]
sorted
=
selectionSort
.
sort
(
arr
);
// Output => 1 4 6 9 12 23 54 78 231
SortUtils
.
print
(
sorted
);
// String Input
String
[]
strings
= {
"c"
,
"a"
,
"e"
,
"b"
,
"d"
};
String
[]
sortedStrings
=
selectionSort
.
sort
(
strings
);
//Output => a b c d e
SortUtils
.
print
(
sortedStrings
);
}
}
Back
|
FazBrowse Home
|
New Git URL