-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCycleSortDuplicateElements.java
More file actions
40 lines (33 loc) · 1.17 KB
/
Copy pathCycleSortDuplicateElements.java
File metadata and controls
40 lines (33 loc) · 1.17 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
package Sorting;
import java.util.Arrays;
// cycle sort doesn't fully sort the array if there are duplicate entries
// there is no other specific technique for completely sorting array with duplicate entries using cycle sort
public class CycleSortDuplicateElements {
public static void main(String[] args) {
int[] arr = {2,0,2,1,1,0};
System.out.println(Arrays.toString(cyclicSort(arr)));
}
static int[] cyclicSort(int[] arr) {
int i = 0;
while (i < arr.length) {
int correct = arr[i] - 1;
// check range + avoid infinite loop with duplicates
if (arr[i] > 0 && arr[i] <= arr.length && arr[i] != arr[correct])
swap(arr, i, correct);
else
i++;
}
// for (int j = 0; j < arr.length; j++) {
// if (arr[j] != j + 1) {
// System.out.println("Duplicate: " + arr[j]);
// System.out.println("Missing: " + (j + 1));
// }
// }
return arr;
}
static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}