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.
Examples:
Input: arr[] = {1, 2, 3, 5, 4, 7, 10}
Output: arr[] = {7, 5, 3, 1, 2, 4, 10}
Input: arr[] = {0, 4, 5, 3, 7, 2, 1}
Output: arr[] = {7, 5, 3, 1, 0, 2, 4}
Naive Approach-
The idea is to store all even in a separate array or vector and sort them in ascending order and then store all odd in a separate array or vector and sort them in descending order. Then replace all input array elements with those odd array/vector elements followed by even array/vector elements
Steps to implement-
- Declare two vectors odd and even to store odd and even elements
- Run a for loop on the input array to separately store odd and even elements into odd and even vector
- Then sort even elements in ascending order and odd elements in decreasing order
- Then, first copy odd elements into the original array and then even elements into that array
Code-
C++
#include <bits/stdc++.h>
using namespace std;
void twoWaySort( int arr[], int n)
{
vector< int > odd;
vector< int > even;
for ( int i=0;i<n;i++){
if (arr[i]%2==0){even.push_back(arr[i]);}
else {odd.push_back(arr[i]);}
}
sort(even.begin(),even.end());
sort(odd.begin(),odd.end(),greater< int >());
int i=0;
for ( int j=0;j<odd.size();j++){
arr[i]=odd[j];
i++;
}
for ( int j=0;j<even.size();j++){
arr[i]=even[j];
i++;
}
}
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;
}
|
Java
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void twoWaySort( int [] arr) {
List<Integer> odd = new ArrayList<>();
List<Integer> even = new ArrayList<>();
for ( int i = 0 ; i < arr.length; i++) {
if (arr[i] % 2 == 0 ) {
even.add(arr[i]);
}
else {
odd.add(arr[i]);
}
}
Collections.sort(even);
Collections.sort(odd, Collections.reverseOrder());
int i = 0 ;
for ( int j = 0 ; j < odd.size(); j++) {
arr[i] = odd.get(j);
i++;
}
for ( int j = 0 ; j < even.size(); j++) {
arr[i] = even.get(j);
i++;
}
}
public static void main(String[] args) {
int [] arr = { 1 , 3 , 2 , 7 , 5 , 4 };
twoWaySort(arr);
for ( int i = 0 ; i < arr.length; i++) {
System.out.print(arr[i] + " " );
}
}
}
|
Python3
def twoWaySort(arr, n):
odd = []
even = []
for i in range (n):
if arr[i] % 2 = = 0 :
even.append(arr[i])
else :
odd.append(arr[i])
even.sort()
odd.sort(reverse = True )
i = 0
for j in range ( len (odd)):
arr[i] = odd[j]
i + = 1
for j in range ( len (even)):
arr[i] = even[j]
i + = 1
arr = [ 1 , 3 , 2 , 7 , 5 , 4 ]
n = len (arr)
twoWaySort(arr, n)
for i in range (n):
print (arr[i], end = " " )
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void TwoWaySort( int [] arr, int n)
{
List< int > odd = new List< int >();
List< int > even = new List< int >();
for ( int i = 0; i < n; i++) {
if (arr[i] % 2 == 0) {
even.Add(arr[i]);
}
else {
odd.Add(arr[i]);
}
}
even.Sort();
odd.Sort();
odd.Reverse();
int index = 0;
foreach ( int number in odd)
{
arr[index] = number;
index++;
}
foreach ( int number in even)
{
arr[index] = number;
index++;
}
}
static void Main( string [] args)
{
int [] arr = { 1, 3, 2, 7, 5, 4 };
int n = arr.Length;
TwoWaySort(arr, n);
for ( int i = 0; i < n; i++) {
Console.Write(arr[i] + " " );
}
}
}
|
Javascript
function twoWaySort(arr) {
let odd = [];
let even = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 === 0) {
even.push(arr[i]);
}
else {
odd.push(arr[i]);
}
}
even.sort((a, b) => a - b);
odd.sort((a, b) => b - a);
let index = 0;
for (let j = 0; j < odd.length; j++) {
arr[index] = odd[j];
index++;
}
for (let j = 0; j < even.length; j++) {
arr[index] = even[j];
index++;
}
}
let arr = [1, 3, 2, 7, 5, 4];
twoWaySort(arr);
console.log(arr.join( " " ));
|
Time complexity: O(n + n log n) , for sorting even vector and odd vector and running a for loop
Auxiliary Space: O(n), because there are in total n elements in both the vector
Method 1 (Using Partition)
- Partition the input array such that all odd elements are moved to the 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).
Follow the below steps to implement the above idea:
- Initialize two variables l and r to 0 and n-1 respectively.
- Initialize a variable k to 0 which will count the number of odd elements in the array.
- Run a loop while l < r:
a. Find the first even number from the left side of the array by checking if arr[l] is even, if not increment l and k by 1.
b. Find the first odd number from the right side of the array by checking if arr[r] is odd, if not decrement r by 1.
c. Swap the even number at index l with the odd number at index r.
- Sort the first k elements of the array in descending order using the in-built sort function with greater<int>() as the comparator.
- Sort the remaining n-k elements of the array in ascending order using the in-built sort function.
- The sorted array is now ready to be printed.
Below is the implementation of the above idea.
C++
#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;
}
|
Java
import java.util.Arrays;
import java.util.Collections;
public class GFG {
static void twoWaySort(Integer 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)
{
int temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
}
}
Arrays.sort(arr, 0 , k, Collections.
reverseOrder());
Arrays.sort(arr, k, n);
}
public static void main(String[] args)
{
Integer arr[] = { 1 , 3 , 2 , 7 , 5 , 4 };
twoWaySort(arr, arr.length);
System.out.println(Arrays.toString(arr));
}
}
|
Python
def two_way_sort(arr, arr_len):
l, r = 0 , arr_len - 1
k = 0
while (l < r):
while (arr[l] % 2 ! = 0 ):
l + = 1
k + = 1
while (arr[r] % 2 = = 0 and l < r):
r - = 1
if (l < r):
arr[l], arr[r] = arr[r], arr[l]
odd = arr[:k]
even = arr[k:]
odd.sort(reverse = True )
even.sort()
odd.extend(even)
return odd
arr_len = 6
arr = [ 1 , 3 , 2 , 7 , 5 , 4 ]
result = two_way_sort(arr, arr_len)
for i in result:
print ( str (i) + " " ),
|
C#
using System;
using System.Linq;
class GFG {
static 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) {
int temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
}
}
Array.Sort(arr, 0, k);
Array.Reverse(arr, 0, k);
Array.Sort(arr, k, n - k);
}
public static void Main(String[] args)
{
int [] arr = { 1, 3, 2, 7, 5, 4 };
twoWaySort(arr, arr.Length);
Console.WriteLine(String.Join( " " , arr));
}
}
|
Javascript
<script>
function twoWaySort(arr,n)
{
let l = 0, r = n - 1;
let k = 0;
while (l < r)
{
while (arr[l] % 2 != 0)
{
l++;
k++;
}
while (arr[r] % 2 == 0 && l < r)
r--;
if (l < r)
{
let temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
}
}
let odd= new Array(k);
for (let i=0;i<k;i++)
{
odd[i]=arr[i];
}
let even= new Array(n-k);
for (let i=0;i<n-k;i++)
{
even[i]=arr[k+i];
}
odd.sort( function (a,b){ return b-a;});
even.sort( function (a,b){ return a-b;});
return odd.concat(even);
}
let arr=[1, 3, 2, 7, 5, 4 ];
let ans=twoWaySort(arr, arr.length);
for (let i=0;i<ans.length;i++)
{
document.write(ans[i]+ " " );
}
</script>
|
Time complexity: O(n log n)
Auxiliary Space: O(1)
Method 2 (Using negative multiplication) :
- Make all odd numbers negative.
- Sort all numbers.
- Revert the changes made in step 1 to get original elements back.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
void twoWaySort( int arr[], int n)
{
for ( int i = 0; i < n; i++)
if (arr[i] & 1)
arr[i] *= -1;
sort(arr, arr + n);
for ( int i = 0; i < n; i++)
if (arr[i] & 1)
arr[i] *= -1;
}
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;
}
|
Java
import java.util.Arrays;
public class GFG
{
static void twoWaySort( int arr[], int n)
{
for ( int i = 0 ; i < n; i++)
if ((arr[i] & 1 ) != 0 )
arr[i] *= - 1 ;
Arrays.sort(arr);
for ( int i = 0 ; i < n; i++)
if ((arr[i] & 1 ) != 0 )
arr[i] *= - 1 ;
}
public static void main(String[] args)
{
int arr[] = { 1 , 3 , 2 , 7 , 5 , 4 };
twoWaySort(arr, arr.length);
System.out.println(Arrays.toString(arr));
}
}
|
Python3
def twoWaySort(arr, n):
for i in range ( 0 , n):
if (arr[i] & 1 ):
arr[i] * = - 1
arr.sort()
for i in range ( 0 , n):
if (arr[i] & 1 ):
arr[i] * = - 1
arr = [ 1 , 3 , 2 , 7 , 5 , 4 ]
n = len (arr)
twoWaySort(arr, n);
for i in range ( 0 , n):
print (arr[i], end = " " )
|
C#
using System;
public class GFG
{
static void twoWaySort( int [] arr, int n)
{
for ( int i = 0; i < n; i++)
if ((arr[i] & 1) != 0)
arr[i] *= -1;
Array.Sort(arr);
for ( int i = 0; i < n; i++)
if ((arr[i] & 1) != 0)
arr[i] *= -1;
}
public static void Main()
{
int [] arr = { 1, 3, 2, 7, 5, 4 };
twoWaySort(arr, arr.Length);
for ( int i = 0; i < arr.Length; i++)
Console.Write(arr[i] + " " );
}
}
|
Javascript
<script>
function twoWaySort(arr, n)
{
for (let i = 0; i < n; i++)
if (arr[i] & 1)
arr[i] *= -1;
arr.sort((a,b) => a-b);
for (let i = 0; i < n; i++)
if (arr[i] & 1)
arr[i] *= -1;
}
let arr = [ 1, 3, 2, 7, 5, 4 ];
let n = arr.length;
twoWaySort(arr, n);
for (let i = 0; i < n; i++)
document.write(arr[i] + " " );
</script>
|
PHP
<?php
function twoWaySort(& $arr , $n )
{
for ( $i = 0 ; $i < $n ; $i ++)
if ( $arr [ $i ] & 1)
$arr [ $i ] *= -1;
sort( $arr );
for ( $i = 0 ; $i < $n ; $i ++)
if ( $arr [ $i ] & 1)
$arr [ $i ] *= -1;
}
$arr = array (1, 3, 2, 7, 5, 4);
$n = sizeof( $arr );
twoWaySort( $arr , $n );
for ( $i = 0; $i < $n ; $i ++)
echo $arr [ $i ] . " " ;
?>
|
Time complexity: O(n log n)
Auxiliary Space: O(1)
This method may not work when input array contains negative numbers. However, there is a way to handle this. We count the positive odd integers in the input array then sort again. Readers may refer this for implementation.
Method 3 (Using comparator):
This problem can be easily solved by using the inbuilt sort function with a custom compare method. On comparing any two elements there will be three cases:
- When both the elements are even: In this case, the smaller element must appear in the left of the larger element in the sorted array.
- When both the elements are odd: The larger element must appear on left of the smaller element.
- One is odd and the other is even: The element which is odd must appear on the left of the even element.
Below is the implementation of the above approach:
CPP
#include <bits/stdc++.h>
using namespace std;
void printArr( int arr[], int n)
{
for ( int i = 0; i < n; i++)
cout << arr[i] << " " ;
}
bool compare( int a, int b)
{
if (a % 2 == 0 && b % 2 == 0)
return a < b;
if (a % 2 != 0 && b % 2 != 0)
return b < a;
if (a % 2 != 0)
return true ;
return false ;
}
int main()
{
int arr[] = { 1, 3, 2, 7, 5, 4 };
int n = sizeof (arr) / sizeof ( int );
sort(arr, arr + n, compare);
printArr(arr, n);
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class GFG
{
static void printArr(ArrayList<Integer> arr, int n) {
for ( int i = 0 ; i < n; i++)
System.out.print(arr.get(i) + " " );
}
public static void main(String args[]) {
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add( 1 );
arr.add( 3 );
arr.add( 2 );
arr.add( 7 );
arr.add( 5 );
arr.add( 4 );
int n = arr.size();
Collections.sort(arr, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
if (a % 2 == 0 && b % 2 == 0 )
return (a - b);
if (a % 2 != 0 && b % 2 != 0 )
return (b - a);
if (a % 2 != 0 )
return - 1 ;
return 0 ;
}
});
printArr(arr, n);
}
}
|
Python3
from functools import cmp_to_key
def printArr(arr, n):
for i in range (n):
print (arr[i], end = " " )
def compare(a, b):
if (a % 2 = = 0 and b % 2 = = 0 and a < b):
return - 1
if (a % 2 ! = 0 and b % 2 ! = 0 and b > a):
return 1
if (a % 2 ! = 0 ):
return - 1
return 1
arr = [ 1 , 3 , 2 , 7 , 5 , 4 ]
n = len (arr)
arr.sort(key = cmp_to_key(compare))
printArr(arr, n)
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
static void printArr(List< int > arr, int n) {
for ( int i = 0; i < n; i++)
Console.Write(arr[i] + " " );
}
private static int Compare( int a, int b)
{
if (a % 2 == 0 && b % 2 == 0 && a<b)
return -1;
if (a % 2 != 0 && b % 2 != 0 && b>a)
return 1;
if (a % 2 != 0)
return -1;
return 1;
}
public static void Main(String []args) {
List< int > arr = new List< int >();
arr.Add(1);
arr.Add(3);
arr.Add(2);
arr.Add(7);
arr.Add(5);
arr.Add(4);
int n = arr.Count;
arr.Sort(Compare);
printArr(arr, n);
}
}
|
Javascript
<script>
function printArr(arr, n)
{
for (let i = 0; i < n; i++)
document.write(arr[i] + " " );
}
function compare(a, b) {
if (a % 2 == 0 && b % 2 == 0 && a < b)
return -1;
if (a % 2 != 0 && b % 2 != 0 && b > a)
return 1;
if (a % 2 != 0)
return -1;
return 1;
}
var arr = [1, 3, 2, 7, 5, 4];
var n = arr.length;
arr.sort(compare);
printArr(arr, n);
</script>
|
Time complexity : O(n*logn) [sort function has average time complexity n*logn]
Auxiliary Space : O(1)
Thanks to Amandeep Singh for suggesting this solution.
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
13 Sep, 2023
Like Article
Save Article