Skip to content

Commit 0209b07

Browse files
committed
Almost Sorted solution
1 parent f874209 commit 0209b07

File tree

1 file changed

+99
-0
lines changed

1 file changed

+99
-0
lines changed

almost-sorted.cs

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
using System;
2+
using System.Linq;
3+
using System.Collections.Generic;
4+
using System.Text;
5+
6+
namespace ConsoleApplication
7+
{
8+
class Program
9+
{
10+
public static void Main(String[] args)
11+
{
12+
int n = int.Parse(Console.ReadLine());
13+
int[] ar = Array.ConvertAll<string, int>(Console.ReadLine().Trim().Split(' '), e => int.Parse(e));
14+
15+
if(isSorted(ar, n))
16+
{
17+
Console.WriteLine("yes");
18+
return;
19+
}
20+
21+
int a = -1;
22+
int b = -1;
23+
24+
for(int i = 0; i < n - 1; i++)
25+
{
26+
if(ar[i] > ar[i + 1])
27+
{
28+
a = i;
29+
break;
30+
}
31+
}
32+
33+
for(int i = n - 1; i > 0; i--)
34+
{
35+
if(ar[i] < ar[i - 1])
36+
{
37+
b = i;
38+
break;
39+
}
40+
}
41+
42+
if(a != -1 && b != -1)
43+
{
44+
int temp = ar[a];
45+
ar[a] = ar[b];
46+
ar[b] = temp;
47+
48+
if(isSorted(ar, n))
49+
{
50+
Console.WriteLine("yes");
51+
Console.WriteLine($"swap {a + 1} {b + 1}");
52+
return;
53+
}
54+
55+
ar[b] = ar[a];
56+
ar[a] = temp;
57+
}
58+
59+
int[] nar = new int[n];
60+
61+
for(int i = 0; i < a; i++)
62+
{
63+
nar[i] = ar[i];
64+
}
65+
66+
for(int i = 0; i <= b - a; i++)
67+
{
68+
nar[a + i] = ar[b - i];
69+
}
70+
71+
for(int i = b + 1; i < n; i++)
72+
{
73+
nar[i] = ar[i];
74+
}
75+
76+
if(isSorted(nar, n))
77+
{
78+
Console.WriteLine("yes");
79+
Console.WriteLine($"reverse {a + 1} {b + 1}");
80+
return;
81+
}
82+
83+
Console.WriteLine("no");
84+
}
85+
86+
public static bool isSorted(int[] ar, int n)
87+
{
88+
for(int i = 1; i < n; i++)
89+
{
90+
if(ar[i] < ar[i - 1])
91+
{
92+
return false;
93+
}
94+
}
95+
96+
return true;
97+
}
98+
}
99+
}

0 commit comments

Comments
 (0)