TheAlgorithms-C/sorting/shaker_sort.c

40 lines
764 B
C
Raw Normal View History

2017-05-04 21:21:39 +03:00
#include <stdio.h>
#include <stdlib.h>
2017-05-04 21:21:39 +03:00
void swap(int *a, int *b)
{
2017-05-04 21:21:39 +03:00
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void shakersort(int *a, int n)
2017-05-04 21:21:39 +03:00
{
int p, i;
for (p = 1; p <= n / 2; p++)
{
for (i = p - 1; i < n - p; i++)
if (a[i] > a[i + 1])
{
2017-05-04 21:21:39 +03:00
swap(&a[i], &a[i + 1]);
}
2017-05-04 21:21:39 +03:00
for (i = n - p - 1; i >= p; i--)
if (a[i] < a[i - 1])
{
2017-05-04 21:21:39 +03:00
swap(&a[i], &a[i - 1]);
}
2017-05-04 21:21:39 +03:00
}
}
int main()
{
int n;
scanf("%d", &n);
int *arr = (int *)malloc(n * sizeof(int));
int i;
for (i = 0; i < n; i++) scanf("%d ", &arr[i]);
2017-05-04 21:21:39 +03:00
shakersort(arr, n);
for (i = 0; i < n; i++) printf("%d ", arr[i]);
free(arr);
2017-05-04 21:21:39 +03:00
return 0;
}