-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathodd_even_transposition_sort.c
More file actions
82 lines (75 loc) · 2.15 KB
/
odd_even_transposition_sort.c
File metadata and controls
82 lines (75 loc) · 2.15 KB
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
80
81
82
// Required libraries
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
// Structure for arguments
typedef struct{
int *arr;
int n;
int index;
}arguments;
// Utility function to print the array
void printArray(int *arr, int n){
for(int i = 0; i < n;i ++){
printf("%d ",arr[i]);
}
printf("\n");
}
// Comparison in each process
void *compare(void *arg){
arguments *args = (arguments*)arg;
int index = args->index;
int temp = args->arr[index];
if((index + 1 < args->n) && (args->arr[index + 1] < args->arr[index])){
args->arr[index] = args->arr[index+1];
args->arr[index + 1] = temp;
}
}
// Main function performing the odd even transposition sort
void oddEvenTranspositionSort(int arr[], int n){
int max_threads = (n + 1) / 2;
pthread_t threads[max_threads];
arguments *args = (arguments*)malloc(sizeof(arguments));
args->arr = arr;
args->n = n;
// For n rounds
for(int i = 1; i <= n; i ++){
// Odd exchanges
if(i % 2 == 1){
int index = 0;
for(int j = 0; j < max_threads; j ++){
args->index = index;
pthread_create(&threads[j], NULL, compare, (void *)args);
index += 2;
pthread_join(threads[j], NULL);
}
}
// Even exchanges
else{
int index = 1;
for(int j = 0; j < max_threads - 1; j ++){
args->index = index;
pthread_create(&threads[j], NULL, compare, (void *)args);
index += 2;
pthread_join(threads[j], NULL);
}
}
}
}
// Driver function of the program
int main(){
int n;
// Input
printf("Enter the number of elements in your sequence:\n");
scanf("%d",&n);
int arr[n];
printf("Enter your sequence:\n");
for(int i = 0;i < n; i ++){
scanf("%d",&arr[i]);
}
oddEvenTranspositionSort(arr,n);
// Output
printf("By odd even transposition sort, the sorted sequence is:\n");
printArray(arr,n);
return 0;
}