using
System;
using
System.Collections.Generic;
public
class
GFG
{
static
void
Rearrange(
int
[]arr,
int
K,
int
N)
{
int
[]ans =
new
int
[N + 1];
int
f = -1;
for
(
int
i = 0; i < N; i++) {
ans[i] = -1;
}
for
(
int
i = 0; i < arr.Length; i++)
{
if
(arr[i] == K)
{
K = i;
break
;
}
}
List<
int
> smaller =
new
List<
int
>();
List<
int
> greater =
new
List<
int
>();
for
(
int
i = 0; i < N; i++) {
if
(arr[i] < arr[K])
smaller.Add(arr[i]);
else
if
(arr[i] > arr[K])
greater.Add(arr[i]);
}
int
low = 0, high = N - 1;
while
(low <= high) {
int
mid = (low + high) / 2;
if
(mid == K) {
ans[mid] = arr[K];
f = 1;
break
;
}
else
if
(mid < K) {
if
(smaller.Count == 0) {
break
;
}
ans[mid] = smaller[smaller.Count-1];
smaller.RemoveAt(smaller.Count-1);
low = mid + 1;
}
else
{
if
(greater.Count == 0) {
break
;
}
ans[mid] = greater[greater.Count-1];
greater.RemoveAt(greater.Count-1);
high = mid - 1;
}
}
if
(f == -1) {
Console.WriteLine(-1 );
return
;
}
for
(
int
i = 0; i < N; i++) {
if
(ans[i] == -1) {
if
(smaller.Count>0) {
ans[i] = smaller[smaller.Count-1];
smaller.RemoveAt(smaller.Count-1);
}
else
if
(greater.Count>0) {
ans[i] = greater[greater.Count-1];
greater.RemoveAt(greater.Count-1);
}
}
}
for
(
int
i = 0; i < N; i++)
Console.Write(ans[i] +
" "
);
Console.WriteLine();
}
public
static
void
Main(String []args)
{
int
[]arr = { 10, 7, 2, 5, 3, 8 };
int
K = 7;
int
N = arr.Length;
Rearrange(arr, K, N);
}
}