-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAlternateTimeOptimalSorting.java
More file actions
104 lines (87 loc) · 2.99 KB
/
AlternateTimeOptimalSorting.java
File metadata and controls
104 lines (87 loc) · 2.99 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
103
104
import java.util.Scanner;
public class AlternateTimeOptimalSorting {
static void printArray(int[] arr) {
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static int minimum(int a, int b) {
return a < b ? a : b;
}
static int maximum(int a, int b) {
return a > b ? a : b;
}
static int send(int[] arr, int index) {
return arr[index];
}
static void receive(int[] arr, int index, int value) {
arr[index] = value;
}
static void compute(int[] arr, int n, int center) {
if (center - 1 < 0) {
int receivedRight = send(arr, center + 1);
if (arr[center] > receivedRight) {
swap(arr, center, center + 1);
}
} else if (center + 1 >= n) {
int receivedLeft = send(arr, center - 1);
if (arr[center] < receivedLeft) {
swap(arr, center, center - 1);
}
}
else {
int left = send(arr, center - 1);
int right = send(arr, center + 1);
int current = send(arr, center);
int minValue = minimum(current, minimum(left, right));
int maxValue = maximum(current, maximum(left, right));
int midValue = current + left + right - minValue - maxValue;
receive(arr, center - 1, minValue);
receive(arr, center + 1, maxValue);
receive(arr, center, midValue);
}
}
static void alternateTimeOptimalSorting(int[] arr, int n) {
for (int i = 1; i < n; i++) {
int remainder = (i + 1) % 3;
int j;
if (remainder == 0) {
j = 2;
} else if (remainder == 1) {
j = 0;
} else {
j = 1;
}
while (j < n) {
compute(arr, n, j);
j += 3;
}
System.out.println("Step " + i + ":");
printArray(arr);
}
}
public static void main(String[] args) {
// Input
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of elements in your sequence:");
int n = sc.nextInt();
int[] arr = new int[n];
System.out.println("Enter your sequence:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
long startTime = System.currentTimeMillis();
alternateTimeOptimalSorting(arr, n);
System.out.println("By alternate time optimal sorting method, the sorted sequence is:");
printArray(arr);
long endTime = System.currentTimeMillis();
System.out.println("Execution time: " + (endTime - startTime) + " ms");
sc.close();
}
}