Skip to content

Commit 1c1d8fc

Browse files
committed
feat: fix wrong implementation of cyclic sort
1 parent e915629 commit 1c1d8fc

File tree

1 file changed

+5
-4
lines changed

1 file changed

+5
-4
lines changed

src/main/java/algorithms/sorting/cyclicSort/generalised/CyclicSort.java

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,18 +13,19 @@ public class CyclicSort {
1313
*/
1414
public static void cyclicSort(int[] arr, int n) {
1515
for (int currIdx = 0; currIdx < n - 1; currIdx++) {
16-
int currElement = arr[currIdx];
16+
int currElement;
1717
int rightfulPos;
1818

1919
do {
2020
rightfulPos = currIdx; // initialization since elements before currIdx are correctly placed
21+
currElement = arr[currIdx];
2122
for (int i = currIdx + 1; i < n; i++) { // O(n) find rightfulPos for the currElement
2223
if (arr[i] < currElement) {
2324
rightfulPos++;
2425
}
25-
if (rightfulPos == currIdx) { // verified curr position is correct for curr element
26-
break;
27-
}
26+
}
27+
if (rightfulPos == currIdx) { // verified curr position is correct for curr element
28+
break;
2829
}
2930
while (currElement == arr[rightfulPos]) { // duplicates found, so find next suitable position
3031
rightfulPos++;

0 commit comments

Comments
 (0)