-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalmostsorted.c
More file actions
130 lines (114 loc) · 2.13 KB
/
almostsorted.c
File metadata and controls
130 lines (114 loc) · 2.13 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
// https://www.hackerrank.com/challenges/almost-sorted/problem
#include <stdio.h>
int size, i;
// Checking is Array Sorted!!
int isSorted(int arr[], int start)
{
for (i = start; i < size - 1; i++)
{
if (arr[i] > arr[i + 1])
{
return i;
}
}
return -1;
}
// Can Swap do the work?
int canSwap(int arr[], int point)
{
int end = point + 1;
for (i = end; i < size; i++)
{
if (arr[point] < arr[i])
{
end = i - 1;
break;
}
}
int temp = arr[point];
arr[point] = arr[end];
arr[end] = temp;
if (isSorted(arr, 0) == -1)
{
return end;
}
else
{
return -1;
}
}
int canReverse(int arr[], int point)
{
int end = point + 1;
for (i = end; i < size - 1; i++)
{
if (arr[i] > arr[i + 1])
{
end = i + 1;
}
else
{
break;
}
}
int limit = (end - point) / 2;
for (i = 0; i <= limit; i++)
{
int temp = arr[point + i];
arr[point + i] = arr[end - i];
arr[end - i] = temp;
}
if (point - 1 >= 0)
{
if (isSorted(arr, point - 1) == -1)
{
return end;
}
}
else
{
if (isSorted(arr, point) == -1)
{
return end;
}
}
return -1;
}
int main(void)
{
scanf(" %d", &size);
int Arr[size], temp1[size], temp2[size];
for (i = 0; i < size; i++)
{
scanf(" %d", &Arr[i]);
temp1[i] = Arr[i];
temp2[i] = Arr[i];
}
int point = isSorted(Arr, 0);
if (point != -1)
{
int end = canSwap(temp1, point);
if (end != -1)
{
printf("yes\nswap %d %d", point + 1, end + 1);
}
else
{
end = canReverse(temp2, point);
if (end != -1)
{
printf("yes\nreverse %d %d", point + 1, end + 1);
}
else
{
printf("no");
}
}
}
else
{
printf("yes");
}
printf("\n");
return 0;
}