|
| 1 | +// C++ program to implement Circle Sort |
| 2 | + |
| 3 | +#include<bits/stdc++.h> |
| 4 | +using namespace std; |
| 5 | + |
| 6 | +/* |
| 7 | +Performs recursive circular swaps and returns true if atleast one swap occurs |
| 8 | +*/ |
| 9 | +bool rec_sort(int arr[], int beg, int end) |
| 10 | +{ |
| 11 | + bool isSwap = false; |
| 12 | + |
| 13 | + // If concerned array is empty, Return |
| 14 | + if (beg == end) |
| 15 | + return false; |
| 16 | + |
| 17 | + // Storing the values of beg, end to later use in the recursive call |
| 18 | + int begA, endA; |
| 19 | + for(begA = beg, endA = end; begA < endA; begA++, endA--) |
| 20 | + { |
| 21 | + //Compares the first and last elements |
| 22 | + if (arr[begA] > arr[endA]) |
| 23 | + { |
| 24 | + swap(arr[begA], arr[endA]); |
| 25 | + isSwap = true; |
| 26 | + } |
| 27 | + |
| 28 | + } |
| 29 | + |
| 30 | + // If the array has odd number of elements |
| 31 | + if (begA == endA) |
| 32 | + if (arr[begA] > arr[endA + 1]) |
| 33 | + { |
| 34 | + swap(arr[beg], arr[endA+1]); |
| 35 | + isSwap = true; |
| 36 | + } |
| 37 | + |
| 38 | + int mid = (end - beg) / 2; |
| 39 | + bool isSwapA = rec_sort(arr, beg, beg+mid); |
| 40 | + bool isSwapB = rec_sort(arr, beg+mid+1, end); |
| 41 | + |
| 42 | + return (isSwap || isSwapA || isSwapB); |
| 43 | +} |
| 44 | + |
| 45 | +void circle_sort(int arr[], int n) |
| 46 | +{ |
| 47 | + while (rec_sort(arr, 0, n-1)) |
| 48 | + { |
| 49 | + |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | + |
| 54 | +int main() |
| 55 | +{ |
| 56 | + int n; |
| 57 | + cout<<"\nHow many numbers do you want to sort? "; |
| 58 | + cin>>n; |
| 59 | + int arr[n]; |
| 60 | + |
| 61 | + if (n <= 0) |
| 62 | + { |
| 63 | + cout<<"The array is Empty!!!"; |
| 64 | + return 0; |
| 65 | + } |
| 66 | + // Input the numbers to sort |
| 67 | + cout<<"Enter the numbers: "; |
| 68 | + for (int i = 0; i < n; i++) |
| 69 | + cin>>arr[i]; |
| 70 | + |
| 71 | + //Call the sort function |
| 72 | + circle_sort(arr,n); |
| 73 | + |
| 74 | + cout<<"The numbers in sorted order is: "; |
| 75 | + // Print the sorted array |
| 76 | + for (int i = 0; i < n; i++) |
| 77 | + cout<<arr[i]<<" "; |
| 78 | + cout<<endl; |
| 79 | + return 0; |
| 80 | +} |
| 81 | + |
| 82 | +/* |
| 83 | +Time Complexity: O(n*log(n)) |
| 84 | +Space Complexity: O(n) |
| 85 | +SAMPLE INPUT AND OUTPUT |
| 86 | +SAMPLE 1 |
| 87 | +How many numbers do you want to sort? 5 |
| 88 | +Enter the numbers: 1 3 5 2 4 |
| 89 | +The numbers in sorted order is: 1 2 3 4 5 |
| 90 | +SAMPLE 2 |
| 91 | +How many numbers do you want to sort? 0 |
| 92 | +The array is Empty!!! |
| 93 | +*/ |
0 commit comments