-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRerange_Array4.cpp
More file actions
47 lines (38 loc) · 1.18 KB
/
Copy pathRerange_Array4.cpp
File metadata and controls
47 lines (38 loc) · 1.18 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
#include <bits/stdc++.h>
using namespace std;
void rearrange(int arr[], int n)
{
int max_idx = n - 1, min_idx = 0;
// store maximum element of array
int max_elem = arr[n - 1] + 1;
// traverse array elements
for (int i = 0; i < n; i++) {
// at even index : we have to put maximum element
if (i % 2 == 0) {
arr[i] += (arr[max_idx] % max_elem) * max_elem;
max_idx--;
}
// at odd index : we have to put minimum element
else {
arr[i] += (arr[min_idx] % max_elem) * max_elem;
min_idx++;
}
}
// array elements back to it's original form
for (int i = 0; i < n; i++)
arr[i] = arr[i] / max_elem;
}
// Driver program to test above function
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Original Arrayn";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
rearrange(arr, n);
cout << "\nModified Array\n";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}