I have two solutions for this problem, but which is one is optimal?
A list of N numbers is given. The player has to arrange the numbers so that all the odd numbers of the list come after the even numbers. Write an algorithm to arrange the given list such that all the odd numbers of the list come after the even numbers.
Input
The first line of the input consists of an integer numbers, representing the size of the list(N). The second line of the input consists of N space-separated integers representing the values of the list
Output
Print N space-separated integers such that all the odd numbers of the list come after the even numbers
Example
Sample Input
8
10 98 3 33 12 22 21 11Sample Output
10 98 12 22 3 33 21 11
Solution no1-
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
int a[n];
for(int i=0; i<n; i++)
cin>>a[i];
int p1=0, p2= n-1;
while(p1 < p2){
while(a[p1]%2 == 0 and p1<p2)
p1++;
while(a[p2]%2 != 0 and p1<p2)
p2--;
if(p1 < p2){
swap(a[p1], a[p2]);
p1++;
p2--;
}
}
for(int i=0; i<n; i++)
cout<<a[i]<<" ";
return 0;
}
solution 2-
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
for(int i=0;i<n;i++){
if(arr[i]%2==0)
cout<<arr[i]<<" ";
}
for(int i=0;i<n;i++){
if(arr[i]%2!=0)
cout<<arr[i]<<" ";
}
return 0;
}