diff --git a/Sorting_Algorithms/CyclicSort.cpp b/Sorting_Algorithms/CyclicSort.cpp new file mode 100644 index 0000000..3a72a60 --- /dev/null +++ b/Sorting_Algorithms/CyclicSort.cpp @@ -0,0 +1,30 @@ +#include +#include + +using namespace std; + +void cyclicSort(vector& arr) { + int n = arr.size(); + for (int i = 0; i < n; i++) { + while (arr[i] != i + 1) { + if (arr[i] <= 0 || arr[i] > n || arr[i] == arr[arr[i] - 1]) { + break; + } + swap(arr[i], arr[arr[i] - 1]); + } + } +} + +int main() { + vector arr = {4, 2, 3, 1, 5}; + + cyclicSort(arr); + + cout << "Sorted array: "; + for (int num : arr) { + cout << num << " "; + } + cout << endl; + + return 0; +}