forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCycleSort.java
More file actions
87 lines (66 loc) · 2.29 KB
/
CycleSort.java
File metadata and controls
87 lines (66 loc) · 2.29 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
package com.sorts;
public class CycleSort {
/**
* @param arr Array to be sorted
* @param <T> Generic type
* @return arr Sorted array
*/
public <T extends Comparable<T>> T[] sort(T[] arr) {
int n = arr.length;
// Counter for the number of memory writes
int count = 0;
// Traverse array and put the elements on their respective right places
for (int i = 0; i < n - 1; i++) {
// Initialize item as the starting point
T item = arr[i];
// Find the position where we want to put the item
// Basically we count all the smaller elements to the right of the item
int position = i;
for (int j = i + 1; j < n; j++) {
if (arr[j].compareTo(item) < 0) {
position++;
}
}
// Check if the element is already at the correct position...
if (position == i) {
// .. then we do not have to do anything
continue;
}
// Ignore duplicate elements
while (item == arr[position]) {
position++;
}
// Put the elements at its right position
if (position != i) {
// Swap
T temp = item;
item = arr[position];
arr[position] = temp;
count++;
}
// Rotate remaining cycle
while (position != i) {
position = i;
// Find the position where we put the element
for (int j = i + 1; j < n; j++) {
if (arr[j].compareTo(item) < 0) {
position++;
}
}
// Ignore duplicate elements
while (item == arr[position]) {
position++;
}
// Put the element to its correct position
if (item != arr[position]) {
T temp = arr[position];
arr[position] = item;
item = temp;
count++;
}
}
}
System.out.println("Number of memory writes :: " + count);
return arr;
}
}