Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Sort the given Array as per given conditions
Next article icon

Sort the given Array as per given conditions

Last Updated : 20 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;  // Function to sort array in the way // mentioned above void AwesomeSort(vector<int> m, int n) {     // Create three vectors     vector<int> v1, v2, v3;      int i;      // Traverse through the elements     // of the array     for (i = 0; i < n; i++) {          // If elements are even and         // divisible by 10         if (m[i] % 10 == 0)             v1.push_back(m[i]);          // If number is even but not divisible         // by 5         else if (m[i] % 2 == 0)             v2.push_back(m[i]);         else             // If number is odd             v3.push_back(m[i]);     }      // Sort  v1 in descending order     sort(v1.begin(), v1.end(), greater<int>());      for (int i = 0; i < v1.size(); i++) {         cout << v1[i] << " ";     }     for (int i = v2.size()-1; i >= 0; i--) {         cout << v2[i] << " ";     }     for (int i = 0; i < v3.size(); i++) {         cout << v3[i] << " ";     } }  // Driver Code int main() {     // Given Input     vector<int> arr{ 5, 10, 30, 7 };     int N = arr.size();      // FunctionCall     AwesomeSort(arr, N);      return 0; } 
Java
// Java program for the above approach import java.util.Collections; import java.util.Vector;  public class GFG_JAVA {      // Function to sort array in the way     // mentioned above     static void AwesomeSort(Vector<Integer> m, int n)     {         // Create three vectors         Vector<Integer> v1 = new Vector<>();         Vector<Integer> v2 = new Vector<>();         Vector<Integer> v3 = new Vector<>();          int i;          // Traverse through the elements         // of the array         for (i = 0; i < n; i++) {              // If elements are even and             // divisible by 10             if (m.get(i) % 10 == 0)                 v1.add(m.get(i));              // If number is even but not divisible             // by 5             else if (m.get(i) % 2 == 0)                 v2.add(m.get(i));             else                 // If number is odd                 v3.add(m.get(i));         }          // Sort  v1 in descending orde         Collections.sort(v1, Collections.reverseOrder());          for (int ii = 0; ii < v1.size(); ii++) {             System.out.print(v1.get(ii) + " ");         }         for (int ii = v2.size()-1; ii >= 0; ii--) {             System.out.print(v2.get(ii) + " ");         }         for (int ii = 0; ii < v3.size(); ii++) {             System.out.print(v3.get(ii) + " ");         }     }      // Driver code     public static void main(String[] args)     {         // Given Input         Vector<Integer> arr = new Vector<>();         arr.add(5);         arr.add(10);         arr.add(30);         arr.add(7);          int N = arr.size();          // FunctionCall         AwesomeSort(arr, N);     } }  // This code is contributed by abhinavjain194 
Python3
# Python program for the above approach  # Function to sort array in the way # mentioned above def AwesomeSort(m, n):        # Create three vectors     v1, v2, v3 = [],[],[]          # Traverse through the elements     # of the array     for i in range(n):                # If elements are even and         # divisible by 10         if (m[i] % 10 == 0):             v1.append(m[i])          # If number is even but not divisible         # by 5         elif (m[i] % 2 == 0):             v2.append(m[i])         else:             # If number is odd             v3.append(m[i])      # Sort  v1 in descending orde     v1 = sorted(v1)[::-1]      for i in range(len(v1)):         print(v1[i], end = " ")      for i in range(len(v2)-1,-1,-1):         print(v2[i], end = " ")      for i in range(len(v3)):         print (v3[i], end = " ")  # Driver Code if __name__ == '__main__':        # Given Input     arr = [5, 10, 30, 7]     N = len(arr)      # FunctionCall     AwesomeSort(arr, N)      # This code is contributed by mohit kumar 29. 
C#
// C# program for the above approach using System; using System.Collections.Generic; class GFG {          // Function to sort array in the way     // mentioned above     static void AwesomeSort(List<int> m, int n)     {                // Create three vectors         List<int> v1 = new List<int>();         List<int> v2 = new List<int>();         List<int> v3 = new List<int>();           int i;           // Traverse through the elements         // of the array         for (i = 0; i < n; i++) {               // If elements are even and             // divisible by 10             if (m[i] % 10 == 0)                 v1.Add(m[i]);               // If number is even but not divisible             // by 5             else if (m[i] % 2 == 0)                 v2.Add(m[i]);             else                 // If number is odd                 v3.Add(m[i]);         }           // Sort  v1 in descending orde         v1.Sort();         v1.Reverse();           for (int ii = 0; ii < v1.Count; ii++) {             Console.Write(v1[ii] + " ");         }         for (int ii = 0; ii < v2.Count; ii++) {             Console.Write(v2[ii] + " ");         }         for (int ii = 0; ii < v3.Count; ii++) {             Console.Write(v3[ii] + " ");         }     }        static void Main()    {          // Given Input     List<int> arr = new List<int>();     arr.Add(5);     arr.Add(10);     arr.Add(30);     arr.Add(7);      int N = arr.Count;      // FunctionCall     AwesomeSort(arr, N);   } }  // This code is contributed by divyeshrabadiya07. 
JavaScript
<script>  // JavaScript program for the above approach  // Function to sort array in the way // mentioned above function AwesomeSort(m, n) {     // Create three vectors     let v1 = [];     let v2 = [];     let v3 = [];      let i;      // Traverse through the elements     // of the array     for (i = 0; i < n; i++) {          // If elements are even and         // divisible by 10         if (m[i] % 10 == 0)             v1.push(m[i]);          // If number is even but not divisible         // by 5         else if (m[i] % 2 == 0)             v2.push(m[i]);         else             // If number is odd             v3.push(m[i]);     }      // Sort  v1 in descending orde     v1.sort((a, b) => b - a);      for (let i = 0; i < v1.length; i++) {         document.write(v1[i] + " ");     }     for (let i = 0; i < v2.length; i++) {         document.write(v2[i] + " ");     }     for (let i = 0; i < v3.length; i++) {         document.write(v3[i] + " ");     } }  // Driver Code  // Given Input let arr = [5, 10, 30, 7]; let N = arr.length;  // FunctionCall AwesomeSort(arr, N);  </script> 

Output
30 10 5 7 

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


Next Article
Sort the given Array as per given conditions

R

ritmojs
Improve
Article Tags :
  • Sorting
  • C++ Programs
  • Placements
  • CS – Placements
  • DSA
  • Arrays
  • Lowe's Company
Practice Tags :
  • Arrays
  • Sorting

Similar Reads

    C++ Program For Converting Array Into Zig-Zag Fashion
    Given an array of DISTINCT elements, rearrange the elements of array in zig-zag fashion in O(n) time. The converted array should be in form a c e .  Example: Input: arr[] = {4, 3, 7, 8, 6, 2, 1} Output: arr[] = {3, 7, 4, 8, 2, 6, 1} Input: arr[] = {1, 4, 3, 2} Output: arr[] = {1, 4, 2, 3} Recommende
    3 min read
    How to Sort an Array in C++?
    Sorting an array involves rearranging its elements in a specific order such as from smallest to largest element or from largest to smallest element, etc. In this article, we will learn how to sort an array in C++.Example:Input: arr ={5,4,1,2,3}Output: 1 2 3 4 5Explanation: arr is sorted in increasin
    4 min read
    Sort elements of an array A[] placed on a number line by shifting i-th element to (i + B[i])th positions minimum number of times
    Given two arrays A[] and B[] consisting of N positive integers such that each array element A[i] is placed at the ith position on the number line, the task is to find the minimum number of operations required to sort the array elements arranged in the number line. In each operation any array element
    9 min read
    C Program to Sort an Array in Ascending Order
    Sorting an array in ascending order means arranging the elements in the order from smallest element to largest element.The easiest way to sort an array in C is by using qsort() function. This function needs a comparator to know how to compare the values of the array. Let's look at a simple example:C
    3 min read
    Sort an array in descending order based on the sum of its occurrence
    Given an unsorted array of integers which may contain repeated elements, sort the elements in descending order of some of its occurrence. If there exists more than one element whose sum of occurrences are the same then, the one which is greater will come first. Examples: Input: arr[] = [2, 4, 1, 2,
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences