-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcheck_partially_sorted.cpp
More file actions
73 lines (62 loc) · 1.53 KB
/
check_partially_sorted.cpp
File metadata and controls
73 lines (62 loc) · 1.53 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
//
// Created by Mayank Parasar on 2020-03-07.
//
/*
* Check if the vector is partially sorted
* */
#include<iostream>
#include<vector>
using namespace std;
vector<int>sort_func(vector<int> vec) {
bool sort = true;
while(sort) {
sort = false;
for(int ii = 0; ii < vec.size()-1; ii++) {
if(vec[ii] > vec[ii + 1]){
swap(vec[ii], vec[ii+1]);
sort = true;
}
}
}
return vec;
}
// given a value return its index in the sorted array provided above
int binary_search(vector<int>&arr, int val, int start, int end) {
int mid = (start + end) / 2;
int retval = -1;
if( mid > end ) {
return (retval); // not found condition
}else {
if(arr[mid] == val){
retval = mid;
return retval;
}
else if(arr[mid] > val) {
retval=binary_search(arr, val, start, mid - 1);
return(retval);
}
else if(arr[mid] < val) {
retval = binary_search(arr, val, mid+1, end);
return(retval);
}
}
return (retval);
}
int main() {
vector<int> v = {3, 2, 6, 5, 4};
vector<int> v_sorted = sort_func(v);
int k = 2;
cout << boolalpha;
for(int ii = 0; ii < v.size(); ii++) {
int kk = binary_search(v_sorted, v[ii], 0, v_sorted.size());
assert(kk != -1);
if( abs( ii - kk) < k+1)
continue;
else {
cout << false;
return 0;
}
}
cout << true;
return 0;
}