Skip to content

Commit fce63b4

Browse files
Create cycle sort in cpp
1 parent 0e3a690 commit fce63b4

1 file changed

Lines changed: 78 additions & 0 deletions

File tree

CycleSort/cycle sort in cpp

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
// C++ program to impleament 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+
    {
15+
        // initialize item as starting point
16+
        int item = arr[cycle_start];
17+
 
18+
        // Find position where we put the item. We basically
19+
        // count all smaller elements on right side of item.
20+
        int pos = cycle_start;
21+
        for (int i = cycle_start+1; i<n; i++)
22+
            if (arr[i] < item)
23+
                pos++;
24+
 
25+
        // If item is already in correct position
26+
        if (pos == cycle_start)
27+
            continue;
28+
 
29+
        // ignore all duplicate  elements
30+
        while (item == arr[pos])
31+
            pos += 1;
32+
 
33+
        // put the item to it's right position
34+
        if (pos != cycle_start)
35+
        {
36+
            swap(item, arr[pos]);
37+
            writes++;
38+
        }
39+
 
40+
        // Rotate rest of the cycle
41+
        while (pos != cycle_start)
42+
        {
43+
            pos = cycle_start;
44+
 
45+
            // Find position where we put the element
46+
            for (int i = cycle_start+1; i<n; i++)
47+
                if (arr[i] < item)
48+
                    pos += 1;
49+
 
50+
            // ignore all duplicate  elements
51+
            while (item == arr[pos])
52+
                pos += 1;
53+
 
54+
            // put the item to it's right position
55+
            if (item != arr[pos])
56+
            {
57+
                swap(item, arr[pos]);
58+
                writes++;
59+
            }
60+
        }
61+
    }
62+
 
63+
    // Number of memory writes or swaps
64+
    // cout << writes << endl ;
65+
}
66+
 
67+
// Driver program to test above function
68+
int main()
69+
{
70+
    int arr[] = {1, 8, 3, 9, 10, 10, 2, 4 };
71+
    int n = sizeof(arr)/sizeof(arr[0]);
72+
    cycleSort(arr,  n) ;
73+
 
74+
    cout << "After sort : " <<endl;
75+
    for (int i =0; i<n; i++)
76+
        cout << arr[i] << " ";
77+
    return 0;
78+
}

0 commit comments

Comments
 (0)