-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCycleSortGeneral.java
More file actions
70 lines (55 loc) · 1.75 KB
/
CycleSortGeneral.java
File metadata and controls
70 lines (55 loc) · 1.75 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
public class CycleSortGeneral {
public static void cycleSort(int[] arr) {
int n = arr.length;
// Traverse array to place elements at correct position
for (int cycleStart = 0; cycleStart < n - 1; cycleStart++) {
int item = arr[cycleStart];
// Find position where we put the element
int pos = cycleStart;
for (int i = cycleStart + 1; i < n; i++) {
if (arr[i] < item) {
pos++;
}
}
// If element is already in correct position
if (pos == cycleStart) {
continue;
}
// Skip duplicates (if present)
while (item == arr[pos]) {
pos++;
}
// Put item to its right position
if (pos != cycleStart) {
int temp = item;
item = arr[pos];
arr[pos] = temp;
}
// Rotate the rest of the cycle
while (pos != cycleStart) {
pos = cycleStart;
for (int i = cycleStart + 1; i < n; i++) {
if (arr[i] < item) {
pos++;
}
}
while (item == arr[pos]) {
pos++;
}
if (item != arr[pos]) {
int temp = item;
item = arr[pos];
arr[pos] = temp;
}
}
}
}
public static void main(String[] args) {
int[] arr = {20, 40, 50, 10, 30};
cycleSort(arr);
// Print sorted array
for (int num : arr) {
System.out.print(num + " ");
}
}
}