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