Can someone explain why the 2 last sort function in main does not work while the first one works fine.
The program build with no error. Here is the code:
#include <iostream>
#include <vector>
#include <math.h>
#include <algorithm>
using namespace std;
bool comp (int a, int b) {
if (a % 2 == 0) { return 1; }
else { return 0; }
}
int main() {
int n; cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
sort(arr, arr+n, comp);
int pos;
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 1) {
pos = i;
break;
}
}
vector<int> un_sorted;
for (int i = 0; i < n; i++)
{
un_sorted.push_back(arr[i]);
}
//7
//5 9 2 8 6 4 7
//4 6 8 2 5 9 7
sort(un_sorted.begin(), un_sorted.begin()+pos-1);
sort(un_sorted.begin()+pos, un_sorted.end(), greater<int>());
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
}
I was trying to separate an array into 2 part: the odds and the evens and then the even are sort ascending and the odds are sorted descending