Skip to content

Commit d7ccd2f

Browse files
Add Circle Sort (TheAlgorithms#2696)
1 parent e3fde56 commit d7ccd2f

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

Sorts/CircleSort.java

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package Sorts;
2+
3+
import static Sorts.SortUtils.*;
4+
5+
public class CircleSort implements SortAlgorithm {
6+
/* This method implements the circle sort
7+
* @param array The array to be sorted
8+
*/
9+
@Override
10+
public <T extends Comparable<T>> T[] sort(T[] array) {
11+
int n = array.length;
12+
while(doSort(array, 0, n - 1));
13+
return array;
14+
}
15+
16+
/* This method implements the cyclic sort recursive version
17+
* @param array The array to be sorted
18+
* @param the left boundary of the part currently being sorted
19+
* @param the right boundary of the part currently being sorted
20+
*/
21+
private <T extends Comparable<T>> Boolean doSort(T[] array, int left, int right) {
22+
Boolean swapped = false;
23+
24+
if (left == right) {
25+
return false;
26+
}
27+
28+
int low = left;
29+
int high = right;
30+
31+
while (low < high) {
32+
if (array[low].compareTo(array[high]) > 0) {
33+
swap(array, low, high);
34+
swapped = true;
35+
}
36+
low++;
37+
high--;
38+
}
39+
40+
if (low == high && array[low].compareTo(array[high + 1]) > 0) {
41+
swap(array, low, high + 1);
42+
swapped = true;
43+
}
44+
45+
int mid = left + (right - left)/2;
46+
Boolean leftHalf = doSort(array, left, mid);
47+
Boolean rightHalf = doSort(array, mid + 1, right);
48+
49+
return swapped || leftHalf || rightHalf;
50+
}
51+
52+
/* Driver code*/
53+
public static void main(String[] args) {
54+
CircleSort CSort = new CircleSort();
55+
56+
Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12};
57+
CSort.sort(arr);
58+
for (int i = 0; i < arr.length - 1; ++i) {
59+
assert arr[i] <= arr[i + 1];
60+
}
61+
62+
String[] stringArray = {"c", "a", "e", "b", "d"};
63+
CSort.sort(stringArray);
64+
for (int i = 0; i < stringArray.length - 1; ++i) {
65+
assert arr[i].compareTo(arr[i + 1]) <= 0;
66+
}
67+
}
68+
}

0 commit comments

Comments
 (0)