VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sort-the-given-array-as-per-given-conditions/

⇱ Sort the given Array as per given conditions - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sort the given Array as per given conditions

Last Updated : 23 Jul, 2025

Given an array arr[] consisting of N positive integers, the task is to sort the array such that - 

  • All even numbers must come before all odd numbers.
  • All even numbers that are divisible by 5 must come first than even numbers not divisible by 5.
  • If two even numbers are divisible by 5 then the number having a greater value will come first
  • If two even numbers were not divisible by 5 then the number having a greater index in the array will come first.
  • All odd numbers must come in relative order as they are present in the array.

Examples:

Input: arr[] = {5, 10, 30, 7}
Output: 30 10 5 7
Explanation: Even numbers = [10, 30]. Odd numbers = [5, 7]. After sorting of even numbers, even numbers = [30, 10] as both 10 and 30 divisible by 5 but 30 has a larger value so it will come before 10.
After sorting A = [30, 10, 5, 7] as all even numbers must come before all odd numbers.

Approach: This problem can be solved by using sorting. Follow the steps below to solve the problem:

  • Create three vectors say v1, v2, and v3 where v1 stores the numbers which are even and divisible by 5, v2 stores the numbers which are even but not divisible by 5, and v3 stores the numbers which are odd.
  • Iterate in the range [0, N-1] using the variable i and perform the following steps-
    • If arr[i]%2 = 0 and arr[i]%5=0, then insert arr[i] in v1.
    • If arr[i]%2 = 0 and arr[i]%5 != 0, then insert arr[i] in v2.
    • If arr[i]%2 = 1 then insert arr[i] in v3.
  • Sort the vector v1 in descending order.
  • After performing the above steps, print vector v1 then print vector v2 in reverse order, and then v3 as the answer.

Below is the implementation of the above approach:


Output
30 10 5 7 

Time Complexity: O(NlogN)
Auxiliary Space: O(N)

Comment