Ascending order:
Given an array of integers (both odd and even), sort them in such a way that the first part of the array contains even numbers sorted in ascending order, rest portion contains odd numbers sorted in ascending order.
Input : arr[] = {10,7,3,5,1,8,9,2,4,6} Output : arr[] = {2,4,6,8,10,1,3,5,7,9}
#include<bits/stdc++.h>
using namespace std;
bool compare(int a,int b){
if(a%2==0 && b%2==0){
return a<b;
}
else if(a%2!=0 && b%2!=0){
return a<b;
}
else{
return a%2<b%2;
}
}
int main()
{
int a[10]={10,7,3,5,1,8,9,2,4,6};
sort(a,a+10,compare);
for(int i=0;i<10;i++){
printf("%d ",a[i]);
}
return 0;
}
Descending Order:
Given an array of integers (both odd and even), sort them in such a way that the first part of the array contains even numbers sorted in descending order, rest portion contains odd numbers sorted in descending order.
Input : arr[] = {10,7,3,5,1,8,9,2,4,6} Output : arr[] = {10,8,6,4,2,9,7,5,3,1}
#include<bits/stdc++.h>
using namespace std;
bool compare(int a,int b){
if(a%2==0 && b%2==0){
return a>b;
}
else if(a%2!=0 && b%2!=0){
return a>b;
}
else{
return a%2<b%2;
}
}
int main()
{
int a[10]={10,7,3,5,1,8,9,2,4,6};
sort(a,a+10,compare);
for(int i=0;i<10;i++){
printf("%d ",a[i]);
}
return 0;
}
Even Ascending and Odd Descending:
Given an array of integers (both odd and even), sort them in such a way that the first part of the array contains even numbers sorted in ascending order, rest portion contains odd numbers sorted in descending order.
Input : arr[] = {10,7,3,5,1,8,9,2,4,6} Output : arr[] = {2,4,6,8,10,9,7,5,3,1}
#include<bits/stdc++.h>
using namespace std;
bool compare(int a,int b){
if(a%2==0 && b%2==0){
return a<b;
}
else if(a%2!=0 && b%2!=0){
return a>b;
}
else{
return a%2<b%2;
}
}
int main()
{
int a[10]={10,7,3,5,1,8,9,2,4,6};
sort(a,a+10,compare);
for(int i=0;i<10;i++){
printf("%d ",a[i]);
}
return 0;
}
Odd Descending then Even Ascending:
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.
Input : arr[] = {10,7,3,5,1,8,9,2,4,6} Output : arr[] = {9,7,5,3,1,2,4,6,8,10}
#include<bits/stdc++.h>
using namespace std;
bool compare(int a,int b){
if(a%2==0 && b%2==0){
return a<b;
}
else if(a%2!=0 && b%2!=0){
return a>b;
}
else{
return a%2>b%2;
}
}
int main()
{
int a[10]={10,7,3,5,1,8,9,2,4,6};
sort(a,a+10,compare);
for(int i=0;i<10;i++){
printf("%d ",a[i]);
}
return 0;
}
Leave a Reply