-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCheck Sorted Array
More file actions
87 lines (68 loc) · 1.72 KB
/
Check Sorted Array
File metadata and controls
87 lines (68 loc) · 1.72 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
You have been given an array ‘a’ of ‘n’ non-negative integers.You have to check whether the given array is sorted in the non-decreasing order or not.
Your task is to return 1 if the given array is sorted. Else, return 0.
Example :
Input: ‘n’ = 5, ‘a’ = [1, 2, 3, 4, 5]
Output: 1
--------------------------------------------------------------------------------------------------------------------------------------
//brute
#include <bits/stdc++.h>
using namespace std;
bool isSorted(int arr[], int n) {
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[i])
return false;
}
}
return true;
}
int main() {
int arr[] = {1, 2, 3, 4, 5}, n = 5;
bool ans = isSorted(arr, n);
if (ans) cout << "True" << endl;
else cout << "False" << endl;
return 0;
}
------------------------------------------------------------------------------------------
//optimal
using while loop
int i=0;
int isSorted(int n, vector<int> a) {
// Write your code here.
while(i<n-1){
if(a[i]<=a[i+1]){
i++;
}
else
return 0;
}
return 1;
}
//or another using while loop
int i=0;
int isSorted(int n, vector<int> a) {
// Write your code here.
int i=1;
while(i<n){
if(a[i]<a[i-1])
return 0;
else
i++;
}
return 1;
}
----------------------------------------
using for loop
#include<bits/stdc++.h>
using namespace std;
bool isSorted(int arr[], int n) {
for (int i = 1; i < n; i++) {
if (arr[i] < arr[i - 1])
return false;
}
return true;
}
int main() {
int arr[] = {1, 2, 3, 4, 5}, n = 5;
printf("%s", isSorted(arr, n) ? "True" : "False");
}