Given an array A of positive integers. Your task is to 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.

Sradha
1 min readJul 16, 2023
Input:
N = 7
Arr = {1, 2, 3, 5, 4, 7, 10}
Output:
7 5 3 1 2 4 10
Explanation:
Array elements 7 5 3 1 are odd
and sorted in descending order,
whereas 2 4 10 are even numbers
and sorted in ascending order.
class Solution
{

public void sortIt(long arr[], long n)
{
ArrayList<Long> A = new ArrayList<>();
ArrayList<Long> B = new ArrayList<>();

// even numbers
for(int i = 0; i < n; i++)
{
if(arr[i] % 2 == 0)
{
A.add(arr[i]);
}
else
{
B.add(arr[i]);
}
}

Collections.sort(A);//even asc
Collections.sort(B, Collections.reverseOrder());// odd desc
int j, k;
for( j = 0; j < B.size(); j++)
{
arr[j] = B.get(j);
}
for( k = B.size(); k < n; k++)
{

arr[k] = A.get(k - B.size());

}

}
}



--

--

Sradha

sensitive, empathetic.Interested in computer science, animal well being, providing quality education for kids in rural area. Passionate to travelling,teaching.