Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improvement in CycleSort algorithm #194

Closed
hammadsaedi opened this issue Oct 2, 2023 · 2 comments · Fixed by #195
Closed

Improvement in CycleSort algorithm #194

hammadsaedi opened this issue Oct 2, 2023 · 2 comments · Fixed by #195

Comments

@hammadsaedi
Copy link
Contributor

File: master/src/main/java/algorithm/CountingSortSnippet.java

Description:

The cycle sort algorithm has a bug in the following line:

if (arr[i] < n && arr[i] != arr[correctpos])

The bug is that the condition arr[i] < n is not necessary. The algorithm should simply check if the element at i is not in its correct position.

Workaround:

To fix the bug, simply remove the condition arr[i] < n from the following line:

if (arr[i] < n && arr[i] != arr[correctpos])

The corrected line is:

if (arr[i] != arr[correctpos])

Proposed fix:

I propose that we make the following change to the cycleSort() method:

public static int[] cycleSort(int[] arr) {
  int n = arr.length;
  int i = 0;
  while (i < n) {
    int correctpos = arr[i] - 1;
    if (arr[i] != arr[correctpos]) {
      int temp = arr[i];
      arr[i] = arr[correctpos];
      arr[correctpos] = temp;
    } else {
      i++;
    }
  }
  return arr;
}

This change will fix the bug and make the algorithm more efficient.

@hammadsaedi hammadsaedi changed the title Bug in CycleSort algorithm Improvement in CycleSort algorithm Oct 3, 2023
hammadsaedi added a commit to hammadsaedi/30-seconds-of-java that referenced this issue Oct 3, 2023
@hammadsaedi
Copy link
Contributor Author

@iluwatar pls check this out :)

@hammadsaedi
Copy link
Contributor Author

@iluwatar I've done this. You can check PR here:
#195

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Archived in project
Development

Successfully merging a pull request may close this issue.

2 participants