forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shaker_sort.c
80 lines (71 loc) · 1.38 KB
/
shaker_sort.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/* Shaker Sort In C
The algorithm extends the bubble sort by operating in two directions
*/
#include <stdio.h>
void shakersort(int[], int);
void swap(int *, int *);
int main()
{
int num, i, arr[10000];
printf("Enter the number of elements:");
scanf("%d", &num);
for (i = 0; i < num; i++)
{
scanf("%d", &arr[i]);
}
printf("Enter the elements to be sorted:");
for (i = 0; i < num; i++)
{
printf("%d ", arr[i]);
}
shakersort(&arr[0], num);
printf("\n");
printf("Sorted Array:");
for (i = 0; i < num; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
// Sorts the given array bidirectionally
void shakersort(int arr[], int num)
{
int end, start, i;
end = num - 1;
start = 1;
// Bidirectional comparison
while (start <= num / 2)
{
for (i = start - 1; i < end; i++)
{
if (arr[i] > arr[i + 1])
swap(&arr[i], &arr[i + 1]);
}
end = end - 1;
for (i = end; i >= start; i--)
{
if (arr[i] < arr[i - 1])
swap(&arr[i], &arr[i - 1]);
}
start = start + 1;
}
}
// Swaps two elements
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
/*
Sample Output
Enter the number of elements: 13
Enter the elements to be sorted:86 74 -2 -9 67 25 33 86 17 -8 42 10 0
Sorted Array:-9 -8 -2 0 10 17 25 33 42 67 74 86 86
Complexities
Worst case performance:O(n^2)
Best case performance:O(n)
Average performance: O(n^2)
Worst Case Space complexity: O(1)
*/