I was reading about the cycle sort algorithm and found out that it is unstable in nature, however, I am having difficulty in coming up with a case that shows the unstable nature of the cyclic algorithm. Could someone give a case where we can observe the unstable nature of the algorithm?
More information on the algorithm:- https://en.wikipedia.org/wiki/Cycle_sort
Here is my code for Cycle sort algorithm:-
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int *arr;
arr=new int[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
int cyStart, item, pos;
for (int cyStart = 0; cyStart < (n - 1); cyStart++)
{
item = arr[cyStart];
pos = cyStart;
for (int i = cyStart + 1; i < n; i++)
{
if (item > arr[i])
pos++;
}
if (pos == cyStart)
continue;
while (item == arr[pos])
pos++;
if (item != arr[pos])
swap(arr[pos], item);
while (cyStart != pos)
{
pos = cyStart;
for (int i = cyStart + 1; i < n; i++)
{
if (item > arr[i])
pos++;
}
while (item == arr[pos])
pos++;
if (item != arr[pos])
swap(arr[pos], item);
}
}
for(int i=0;i<n;i++)
cout << arr[i] << " ";
return 0;
}