forked from Zubair-droid/hacktoberfest2021
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request Zubair-droid#16 from monarchsharma/main
Rearrange array alternatively
- Loading branch information
Showing
1 changed file
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
//Rearrange array alernatively | ||
//level medium | ||
//company : ZOHO | ||
//This is the most efficient approach with | ||
// Expected Time Complexity: O(N). | ||
// Expected Auxiliary Space: O(1). | ||
#include <bits/stdc++.h> | ||
|
||
using namespace std; | ||
|
||
int main() | ||
{ | ||
int t, n; | ||
//test cases | ||
cin >> t; | ||
while (t--) | ||
{ | ||
//size of array | ||
cin >> n; | ||
long long arr[n]; | ||
//adding elements | ||
for (int i = 0; i < n; i++) | ||
{ | ||
cin >> arr[i]; | ||
} | ||
|
||
int max_index = n - 1; | ||
int min_index = 0; | ||
int max = arr[n - 1] + 1; | ||
|
||
for (int i = 0; i < n; i++) | ||
{ | ||
if (i % 2 == 0) | ||
{ | ||
arr[i] = (arr[max_index] % max) * max + arr[i]; | ||
max_index--; | ||
} | ||
else | ||
{ | ||
arr[i] = (arr[min_index] % max) * max + arr[i]; | ||
min_index++; | ||
} | ||
} | ||
|
||
for (int i = 0; i < n; i++) | ||
{ | ||
arr[i] /= max; | ||
} | ||
//printing elements | ||
for (int i = 0; i < n; i++) | ||
cout << arr[i] << " "; | ||
|
||
cout << "\n"; | ||
} | ||
} |