-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcheck_sort_one_swap.cpp
More file actions
49 lines (42 loc) · 876 Bytes
/
check_sort_one_swap.cpp
File metadata and controls
49 lines (42 loc) · 876 Bytes
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
#include <iostream>
using namespace std;
int checkSorted(int a[], int n)
{
int i, first = 0, second = 0;
int c = 0;
for (i=1; i<n; i++) {
if (a[i] < a[i-1]) {
c++;
if (first == 0)
first = i;
else
second = i;
}
}
if (c > 2)
return false;
if (c == 0)
return true;
if (c == 2)
swap(a[first-1], a[second]);
else if (c == 1)
swap(a[first-1], a[first]);
for (i=1; i<n; i++)
if (a[i] < a[i-1])
return false;
return true;
}
int main()
{
int n, a[100];
cout<<"Enter the size of the array: ";
cin>>n;
cout<<"Enter the elements of the array: ";
for(int i=0; i<n; i++)
cin>>a[i];
if (checkSorted(a, n))
cout << "Yes";
else
cout << "No";
return 0;
}