106k views
3 votes
Cerinţa Se dau două numere naturale nenule n și p. Afișați în ordine crescătoare puterile lui n mai mici sau egale cu p. Date de intrare Programul citește de la tastatură numerele n și p. Date de ieşire Programul afișează pe ecran, în ordine crescătoare, puterile lui n mai mici sau egale cu p, separate prin câte un spațiu. Restricţii şi precizări 2 ≤ n ≤ 10 1 ≤ p < 1.000.000.000

User Jernej K
by
6.6k points

1 Answer

7 votes

Given an array of integers (both odd and even), sort them in such a way that the first part of the array contains odd numbers sorted in descending order, rest portion contains even numbers sorted in ascending order.

Step-by-step explanation:

  • Partition the input array such that all odd elements are moved to left and all even elements on right. This step takes O(n).
  • Once the array is partitioned, sort left and right parts individually. This step takes O(n Log n).

#include <bits/stdc++.h>

using namespace std;

void twoWaySort(int arr[], int n)

{

int l = 0, r = n - 1;

int k = 0;

while (l < r) {

while (arr[l] % 2 != 0) {

l++;

k++;

}

while (arr[r] % 2 == 0 && l < r)

r--;

if (l < r)

swap(arr[l], arr[r]);

}

sort(arr, arr + k, greater<int>());

sort(arr + k, arr + n);

}

int main()

{

int arr[] = { 1, 3, 2, 7, 5, 4 };

int n = sizeof(arr) / sizeof(int);

twoWaySort(arr, n);

for (int i = 0; i < n; i++)

cout << arr[i] << " ";

return 0;

}

User Rjk
by
5.9k points