FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Java/Sorts/CycleSort.java at master · debugmm/Java · GitHub
debugmm
/
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
/
CycleSort.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
71 lines (55 loc) · 1.72 KB
Breadcrumbs
Java
/
Sorts
/
CycleSort.java
Copy path
File metadata and controls
71 lines (55 loc) · 1.72 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
;
import
static
Sorts
.
SortUtils
.
less
;
import
static
Sorts
.
SortUtils
.
print
;
/** @author Podshivalov Nikita (https://github.com/nikitap492) */
class
CycleSort
implements
SortAlgorithm
{
@
Override
public
<
T
extends
Comparable
<
T
>>
T
[]
sort
(
T
[]
arr
) {
int
n
=
arr
.
length
;
// traverse array elements
for
(
int
j
=
0
;
j
<=
n
-
2
;
j
++) {
// initialize item as starting point
T
item
=
arr
[
j
];
// Find position where we put the item.
int
pos
=
j
;
for
(
int
i
=
j
+
1
;
i
<
n
;
i
++)
if
(
less
(
arr
[
i
],
item
))
pos
++;
// If item is already in correct position
if
(
pos
==
j
)
continue
;
// ignore all duplicate elements
while
(
item
.
compareTo
(
arr
[
pos
]) ==
0
)
pos
+=
1
;
// put the item to it's right position
if
(
pos
!=
j
) {
item
=
replace
(
arr
,
pos
,
item
);
}
// Rotate rest of the cycle
while
(
pos
!=
j
) {
pos
=
j
;
// Find position where we put the element
for
(
int
i
=
j
+
1
;
i
<
n
;
i
++)
if
(
less
(
arr
[
i
],
item
)) {
pos
+=
1
;
}
// ignore all duplicate elements
while
(
item
.
compareTo
(
arr
[
pos
]) ==
0
)
pos
+=
1
;
// put the item to it's right position
if
(
item
!=
arr
[
pos
]) {
item
=
replace
(
arr
,
pos
,
item
);
}
}
}
return
arr
;
}
private
<
T
extends
Comparable
<
T
>>
T
replace
(
T
[]
arr
,
int
pos
,
T
item
) {
T
temp
=
item
;
item
=
arr
[
pos
];
arr
[
pos
] =
temp
;
return
item
;
}
public
static
void
main
(
String
[]
args
) {
Integer
arr
[] = {
4
,
23
,
6
,
78
,
1
,
26
,
11
,
23
,
0
, -
6
,
3
,
54
,
231
,
9
,
12
};
CycleSort
cycleSort
=
new
CycleSort
();
cycleSort
.
sort
(
arr
);
System
.
out
.
println
(
"After sort : "
);
print
(
arr
);
}
}
Back
|
FazBrowse Home
|
New Git URL