|
| 1 | +// C++ program to implement cycle sort |
| 2 | +#include <iostream> |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +// Function sort the array using Cycle sort |
| 6 | +void cycleSort(int arr[], int n) |
| 7 | +{ |
| 8 | + // count number of memory writes |
| 9 | + int writes = 0; |
| 10 | + |
| 11 | + // traverse array elements and put it to on |
| 12 | + // the right place |
| 13 | + for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++) { |
| 14 | + // initialize item as starting point |
| 15 | + int item = arr[cycle_start]; |
| 16 | + |
| 17 | + // Find position where we put the item. We basically |
| 18 | + // count all smaller elements on right side of item. |
| 19 | + int pos = cycle_start; |
| 20 | + for (int i = cycle_start + 1; i < n; i++) |
| 21 | + if (arr[i] < item) |
| 22 | + pos++; |
| 23 | + |
| 24 | + // If item is already in correct position |
| 25 | + if (pos == cycle_start) |
| 26 | + continue; |
| 27 | + |
| 28 | + // ignore all duplicate elements |
| 29 | + while (item == arr[pos]) |
| 30 | + pos += 1; |
| 31 | + |
| 32 | + // put the item to it's right position |
| 33 | + if (pos != cycle_start) { |
| 34 | + swap(item, arr[pos]); |
| 35 | + writes++; |
| 36 | + } |
| 37 | + |
| 38 | + // Rotate rest of the cycle |
| 39 | + while (pos != cycle_start) { |
| 40 | + pos = cycle_start; |
| 41 | + |
| 42 | + // Find position where we put the element |
| 43 | + for (int i = cycle_start + 1; i < n; i++) |
| 44 | + if (arr[i] < item) |
| 45 | + pos += 1; |
| 46 | + |
| 47 | + // ignore all duplicate elements |
| 48 | + while (item == arr[pos]) |
| 49 | + pos += 1; |
| 50 | + |
| 51 | + // put the item to it's right position |
| 52 | + if (item != arr[pos]) { |
| 53 | + swap(item, arr[pos]); |
| 54 | + writes++; |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + // Number of memory writes or swaps |
| 60 | + // cout << writes << endl ; |
| 61 | +} |
| 62 | + |
| 63 | +// Driver program to test above function |
| 64 | +int main() |
| 65 | +{ |
| 66 | + int arr[] = { 1, 8, 3, 9, 10, 10, 2, 4 }; |
| 67 | + int n = sizeof(arr) / sizeof(arr[0]); |
| 68 | + cycleSort(arr, n); |
| 69 | + |
| 70 | + cout << "After sort : " << endl; |
| 71 | + for (int i = 0; i < n; i++) |
| 72 | + cout << arr[i] << " "; |
| 73 | + return 0; |
| 74 | +} |
0 commit comments