Skip to content

Commit 69a83c4

Browse files
Create cyclic_sort.cpp
1 parent 987dbb7 commit 69a83c4

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

CPP/sorting/cyclic_sort.cpp

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#include <iostream>
2+
#include <vector>
3+
using namespace std;
4+
5+
// Function to perform cyclic sort
6+
void cyclicSort(vector<int> &arr) {
7+
int i = 0;
8+
while (i < arr.size()) {
9+
int correctIndex = arr[i] - 1; // correct index for current element
10+
if (arr[i] != arr[correctIndex]) {
11+
// swap if current element is not at the correct position
12+
swap(arr[i], arr[correctIndex]);
13+
} else {
14+
i++; // move to next index
15+
}
16+
}
17+
}
18+
19+
int main() {
20+
// Example input
21+
vector<int> arr = {3, 5, 2, 1, 4};
22+
23+
cout << "Before sorting: ";
24+
for (int num : arr)
25+
cout << num << " ";
26+
cout << endl;
27+
28+
cyclicSort(arr);
29+
30+
cout << "After sorting: ";
31+
for (int num : arr)
32+
cout << num << " ";
33+
cout << endl;
34+
35+
return 0;
36+
}

0 commit comments

Comments
 (0)