This C Program implements cyclesort. Cycle sort is an in-place, unstable sorting algorithm, a comparison sort that is theoretically optimal in terms of the total number of writes to the original array, unlike any other in-place sorting algorithm. It is based on the idea that the permutation to be sorted can be factored into cycles, which can individually be rotated to give a sorted result.
Here is source code of the C Program to implement cyclesort. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program to Implement Cyclesort
*/
#include <stdio.h>
#define MAX 8
void cycle_sort(int *);
void main()
{
int a[MAX],i;
printf("enter the elements into array :");
for (i = 0;i < MAX; i++)
{
scanf("%d", &a[i]);
}
cycle_sort(a);
printf("sorted elements are :\n");
for (i = 0;i < MAX; i++)
{
printf("%d", a[i]);
}
}
/* sorts elements using cycle sort algorithm */
void cycle_sort(int * a)
{
int temp, item, pos, i, j, k;
for (i = 0;i < MAX; i++)
{
item = a[i];
pos = i;
do
{
k = 0;
for (j = 0;j < MAX;j++)
{
if (pos != j && a[j] < item)
{
k++;
}
}
if (pos != k)
{
while (pos != k && item == a[k])
{
k++;
}
temp = a[k];
a[k] = item;
item = temp;
pos = k;
}
}while (pos != i);
}
}
$ cc cyclesort.c $ a.out enter the elements into array :7 3 2 5 4 8 9 6 sorted elements are : 23456789 $ a.out enter the elements into array :7 3 2 4 5 4 6 3 sorted elements are : 23344567
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
If you wish to look at programming examples on all topics, go to C Programming Examples.
Next Steps:
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Practice Computer Science MCQs
- Practice BCA MCQs
- Apply for Computer Science Internship
- Buy Computer Science Books
- Apply for C Internship