Skip to content

Commit cea8d03

Browse files
committed
Implemented cycleSort in C
1 parent 2c79947 commit cea8d03

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Diff for: sortingAlgo/cycleSort/cycleSort.c

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
//cycle sort - Sorts an array in minimum swaps
2+
3+
#include<stdio.h>
4+
5+
void cycleSort(int *arr,int n)
6+
{
7+
for(int i=0;i<n-1;i++)
8+
{
9+
int val = arr[i];
10+
int index = i;
11+
for(int j=i+1;j<n;j++)
12+
if(arr[j] < val)
13+
index++;
14+
15+
//if the element is in the correct position
16+
if(index == i)
17+
continue;
18+
19+
//to handle duplicate elements
20+
while(val == arr[index])
21+
index++;
22+
23+
if(index != i){
24+
int temp = val;
25+
val = arr[index];
26+
arr[index] = temp;
27+
}
28+
29+
while(index != i)
30+
{
31+
index = i;
32+
for(int j=i+1;j<n;j++)
33+
if(arr[j] < val)
34+
index++;
35+
while(val == arr[index])
36+
index++;
37+
if(val != arr[index]){
38+
int temp = val;
39+
val = arr[index];
40+
arr[index] = temp;
41+
}
42+
}
43+
}
44+
}
45+
int main()
46+
{
47+
int arr[] = {20,30,10,20,70};
48+
int n = 5;
49+
cycleSort(arr,n);
50+
for (int i = 0; i < n; i++){
51+
printf("%d ", arr[i]);
52+
}
53+
printf("\n");
54+
}
55+

0 commit comments

Comments
 (0)