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

Create cycle_Sort.dart #234

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions sort/cycle_Sort.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
void cycleSort(List<int> arr) {
int n = arr.length;

for (int cycleStart = 0; cycleStart < n - 1; cycleStart++) {
int item = arr[cycleStart];
int pos = cycleStart;

// Find the position to place the current item
for (int i = cycleStart + 1; i < n; i++) {
if (arr[i] < item) {
pos++;
}
}

// Skip if the item is already in its correct position
if (pos == cycleStart) {
continue;
}

// Place the item in its correct position
while (item == arr[pos]) {
pos++;
}
int temp = arr[pos];
arr[pos] = item;
item = temp;

// Rotate the rest of the cycle
while (pos != cycleStart) {
pos = cycleStart;
for (int i = cycleStart + 1; i < n; i++) {
if (arr[i] < item) {
pos++;
}
}

while (item == arr[pos]) {
pos++;
}
temp = arr[pos];
arr[pos] = item;
item = temp;
}
}
}

void main() {
List<int> arr = [64, 34, 25, 12, 22, 11, 90];
print("Original List: $arr");

cycleSort(arr);

print("Sorted List: $arr");
}