import
java.util.*;
public
class
Main {
static
class
Node {
int
data;
Node left, right;
Node(
int
d)
{
data = d;
left =
null
;
right =
null
;
}
}
static
class
iNPair
implements
Comparable<iNPair> {
int
first;
Node second;
iNPair(
int
f, Node s)
{
first = f;
second = s;
}
@Override
public
int
compareTo(iNPair other)
{
return
Integer.compare(first, other.first);
}
}
static
void
pQBasedTraversal(Node root)
{
PriorityQueue<iNPair> pQueue
=
new
PriorityQueue<>();
pQueue.add(
new
iNPair(root.data, root));
while
(!pQueue.isEmpty()) {
iNPair popped_pair = pQueue.poll();
System.out.print(popped_pair.first +
" "
);
if
(popped_pair.second.left !=
null
)
pQueue.add(
new
iNPair(popped_pair.second.left.data,
popped_pair.second.left));
if
(popped_pair.second.right !=
null
)
pQueue.add(
new
iNPair(
popped_pair.second.right.data,
popped_pair.second.right));
}
}
static
Node buildCartesianTreeUtil(
int
root,
int
arr[],
int
parent[],
int
leftchild[],
int
rightchild[])
{
if
(root == -
1
)
return
null
;
Node temp =
new
Node(arr[root]);
temp.left = buildCartesianTreeUtil(
leftchild[root], arr, parent, leftchild,
rightchild);
temp.right = buildCartesianTreeUtil(
rightchild[root], arr, parent, leftchild,
rightchild);
return
temp;
}
static
Node buildCartesianTree(
int
arr[],
int
n)
{
int
parent[] =
new
int
[n];
int
leftchild[] =
new
int
[n];
int
rightchild[] =
new
int
[n];
Arrays.fill(parent, -
1
);
Arrays.fill(leftchild, -
1
);
Arrays.fill(rightchild, -
1
);
int
root =
0
, last;
for
(
int
i =
1
; i <= n -
1
; i++) {
last = i -
1
;
rightchild[i] = -
1
;
while
(arr[last] >= arr[i] && last != root)
last = parent[last];
if
(arr[last] >= arr[i]) {
parent[root] = i;
leftchild[i] = root;
root = i;
}
else
if
(rightchild[last] == -
1
) {
rightchild[last] = i;
parent[i] = last;
leftchild[i] = -
1
;
}
else
{
parent[rightchild[last]] = i;
leftchild[i] = rightchild[last];
rightchild[last] = i;
parent[i] = last;
}
}
parent[root] = -
1
;
return
(buildCartesianTreeUtil(
root, arr, parent, leftchild, rightchild));
}
static
void
printSortedArr(
int
arr[],
int
n)
{
Node root = buildCartesianTree(arr, n);
System.out.println(
"The sorted array is-"
);
pQBasedTraversal(root);
}
public
static
void
main(String[] args)
{
int
[] arr = {
5
,
10
,
40
,
30
,
28
};
int
n = arr.length;
printSortedArr(arr, n);
}
}