Skip to content

Commit

Permalink
Merge pull request #74 from its-amans/main
Browse files Browse the repository at this point in the history
added cycle_sort
  • Loading branch information
lilmistake authored Oct 21, 2023
2 parents da3ceab + 61d8bb5 commit da2780b
Showing 1 changed file with 75 additions and 0 deletions.
75 changes: 75 additions & 0 deletions DSA_Codesheet/Cpp/cycle_sort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#include <iostream>
using namespace std;

void cycleSort (int arr[], int n)
{
// count number of memory writes
int writes = 0;

// traverse array elements and put it to on the right place

for (int i=0; i<=n-2; i++)
{
int item = arr[i];

int pos = i;
for (int j = i+1; j<n; j++)
if (arr[j] < item)
pos++;

// If item is already in correct position then
if (pos == i)
continue;

// if it have duplicate elements
while (item == arr[pos])
pos += 1;

// put the item to right position
if (pos != i)
{
swap(item, arr[pos]);
writes++;
}

// Rotate rest of the cycle
while (pos !=i)
{
pos =i;

// for position where we put the element
for (int j = i+1; j<n; j++)
if (arr[j] < item)
pos += 1;

// to ignore all duplicate elements
while (item == arr[pos])
pos += 1;

// put the item to its right position
if (item != arr[pos])
{
swap(item, arr[pos]);
writes++;
}
}
}
}


int main()
{
int arr[] = {1, 8, 3, 9, 10, 10, 2, 4 };

int n = sizeof(arr)/sizeof(arr[0]);
cout<<"unsorted array:"<<endl;
for (int j =0; j<n; j++)
cout<< arr[j]<<" ";

cycleSort(arr, n) ;
cout<<endl;
cout << "After sort : " <<endl;
for (int j =0; j<n; j++)
cout << arr[j] << " ";
return 0;
}

0 comments on commit da2780b

Please sign in to comment.