Skip to content

Commit af72ad0

Browse files
authored
Merge pull request kothariji#81 from fant0me/master
cycle sort
2 parents 9a0a0e1 + 75bf917 commit af72ad0

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

Sorting/cycle sort

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
// C++ program to implement cycle sort
2+
//added comments to understand code better
3+
#include <iostream>
4+
using namespace std;
5+
6+
// Function sort the array using Cycle sort
7+
void cycleSort(int arr[], int n)
8+
{
9+
// count number of memory writes
10+
int writes = 0;
11+
12+
// traverse array elements and put it to on
13+
// the right place
14+
for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++) {
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+
swap(item, arr[pos]);
36+
writes++;
37+
}
38+
39+
// Rotate rest of the cycle
40+
while (pos != cycle_start) {
41+
pos = cycle_start;
42+
43+
// Find position where we put the element
44+
for (int i = cycle_start + 1; i < n; i++)
45+
if (arr[i] < item)
46+
pos += 1;
47+
48+
// ignore all duplicate elements
49+
while (item == arr[pos])
50+
pos += 1;
51+
52+
// put the item to it's right position
53+
if (item != arr[pos]) {
54+
swap(item, arr[pos]);
55+
writes++;
56+
}
57+
}
58+
}
59+
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

Comments
 (0)