Skip to content

Commit d65cdcf

Browse files
Create BatcherSort.c
1 parent 8aed377 commit d65cdcf

1 file changed

Lines changed: 58 additions & 0 deletions

File tree

‎C/BatcherSort.c‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <time.h>
4+
5+
#define key(A) (A)
6+
#define less(A, B) (key(A) < key(B))
7+
#define exch(A, B) \
8+
{ \
9+
int t = A; \
10+
A = B; \
11+
B = t; \
12+
}
13+
#define compexch(A, B) \
14+
if (less(B, A)) \
15+
exch(A, B)
16+
17+
void batchersort(int a[], int l, int r)
18+
{
19+
int N = r - l + 1;
20+
21+
for (int p = 1; p < N; p += p)
22+
for (int k = p; k > 0; k /= 2)
23+
for (int j = k % p; j + k < N; j += (k + k))
24+
for (int i = 0; i < k; i++)
25+
if (j + i + k < N)
26+
if ((j + i) / (p + p) == (j + i + k) / (p + p))
27+
compexch(a[l + j + i], a[l + j + i + k]);
28+
}
29+
30+
void print_list(int n, int a[])
31+
{
32+
for (int i = 0; i < n; i++)
33+
printf("%d ", a[i]);
34+
printf("\n");
35+
}
36+
37+
int main()
38+
{
39+
int N = 7, i;
40+
int *a;
41+
42+
srand(time(NULL));
43+
44+
a = malloc(N * sizeof(int));
45+
46+
for (i = 0; i < N; i++)
47+
a[i] = rand() % 100;
48+
49+
printf("Before: ");
50+
print_list(N, a);
51+
52+
batchersort(a, 0, N - 1);
53+
54+
printf("After: ");
55+
print_list(N, a);
56+
57+
return 0;
58+
}

0 commit comments

Comments
 (0)