forked from dimpeshmalviya/C-Language-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcyclic_sort.c
More file actions
45 lines (36 loc) · 906 Bytes
/
cyclic_sort.c
File metadata and controls
45 lines (36 loc) · 906 Bytes
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
#include <stdio.h>
// Function to swap two numbers
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Function to perform cyclic sort
void cyclicSort(int arr[], int n) {
int i = 0;
while (i < n) {
int correctIndex = arr[i] - 1;
// If current element is not at its correct position, swap it
if (arr[i] != arr[correctIndex]) {
swap(&arr[i], &arr[correctIndex]);
} else {
i++; // Move to next index
}
}
}
// Function to print the array
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[] = {3, 5, 2, 1, 4};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Before sorting: ");
printArray(arr, n);
cyclicSort(arr, n);
printf("After sorting: ");
printArray(arr, n);
return 0;
}