-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathwave_array.cpp
More file actions
79 lines (58 loc) · 1.87 KB
/
wave_array.cpp
File metadata and controls
79 lines (58 loc) · 1.87 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
/*Given an array Arr (distinct elements) of size N. Rearrange the elements of array in zig-zag fashion. The converted array should be in form a < b > c < d > e < f. The relative order of elements is same in the output i.e you have to iterate on the original array only.
Example 1:
Input:
N = 7
Arr[] = {4, 3, 7, 8, 6, 2, 1}
Output: 3 7 4 8 2 6 1
Explanation: 3 < 7 > 4 < 8 > 2 < 6 > 1
Example 2:
Input:
N = 4
Arr[] = {1, 4, 3, 2}
Output: 1 4 2 3
Explanation: 1 < 4 > 2 < 3
Your Task:
You don't need to read input or print anything. Your task is to complete the function zigZag() which takes the array of integers arr and n as parameters and returns void. You need to modify the array itself.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 10^5
0 <= Arri <= 10^6*/
/********************************************************************************************************************************************************
This solution is with O(n) approach.
O(n*logn) approach would be to sort the array and swap adjacent elements.
Their are different solutions possible. If they ask to give the lexicographically smallest (asked in InterviewBit) solution then use O(n*logn) approach.
*********************************************************************************************************************************************************/
#include <iostream>
using namespace std;
void zigZag(int arr[], int n)
{
// code here
bool flag = true;
for (int i = 0; i < n-1; i++)
{
if (flag)
{
if(arr[i] > arr[i+1])
swap(arr[i], arr[i+1]);
}
else
{
if (arr[i] < arr[i+1])
swap(arr[i], arr[i+1]);
}
flag = !flag;
}
}
int main()
{
int arr[] = {4, 3, 7, 8, 6, 2, 1};
int n = 7;
zigZag(arr, n);
for (int i = 0; i < n; ++i)
{
cout << arr[i] << " ";
}
cout << endl;
return 0;
}