-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOddEvenTranspositionSort.java
More file actions
102 lines (86 loc) · 3.03 KB
/
OddEvenTranspositionSort.java
File metadata and controls
102 lines (86 loc) · 3.03 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import java.util.*;
public class OddEvenTranspositionSort {
static class Process {
int id;
int value;
Integer buffer = null;
Process(int id, int value) {
this.id = id;
this.value = value;
}
void send(Process neighbor) {
neighbor.buffer = this.value;
}
int receive() {
return this.buffer;
}
void compute(boolean isLeft, Process neighbor) {
if (buffer != null) {
if (isLeft && buffer > this.value) {
int temp = this.value;
this.value = buffer;
neighbor.value = temp;
} else if (!isLeft && buffer < this.value) {
int temp = this.value;
this.value = buffer;
neighbor.value = temp;
}
}
this.buffer = null;
}
}
static void oddEvenSort(int[] arr) {
int n = arr.length;
Process[] processes = new Process[n];
for (int i = 0; i < n; i++) {
processes[i] = new Process(i, arr[i]);
}
System.out.println("Initial State:");
printState(processes);
for (int step = 1; step <= n; step++) {
System.out.println("Step " + step + (step % 2 == 1 ? " (Odd Phase):" : " (Even Phase):"));
if (step % 2 == 1) {
for (int i = 0; i + 1 < n; i += 2) {
processes[i].send(processes[i + 1]);
}
for (int i = 0; i + 1 < n; i += 2) {
processes[i + 1].compute(true, processes[i]);
}
} else {
for (int i = 1; i + 1 < n; i += 2) {
processes[i].send(processes[i + 1]);
}
for (int i = 1; i + 1 < n; i += 2) {
processes[i + 1].compute(true, processes[i]);
}
}
printState(processes);
}
System.out.println("Final Sorted Sequence:");
for (Process p : processes) {
System.out.print(p.value + " ");
}
System.out.println();
}
static void printState(Process[] processes) {
for (Process p : processes) {
System.out.print(p.value + " ");
}
System.out.println();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of elements:");
int n = sc.nextInt();
int[] arr = new int[n];
System.out.println("Enter the elements:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
long startTime = System.currentTimeMillis();
oddEvenSort(arr);
long endTime = System.currentTimeMillis();
System.out.println("Execution time: " + (endTime - startTime) + " ms");
sc.close();
}
}