VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sort-elements-basis-number-factors/

⇱ Sort elements on the basis of number of factors - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sort elements on the basis of number of factors

Last Updated : 7 Mar, 2023

Given an array of positive integers. Sort the given array in decreasing order of number of factors of each element, i.e., element having the highest number of factors should be the first to be displayed and the number having least number of factors should be the last one. Two elements with equal number of factors should be in the same order as in the original array.
Examples: 
 

Input : {5, 11, 10, 20, 9, 16, 23}
Output : 20 16 10 9 5 11 23
Number of distinct factors:
For 20 = 6, 16 = 5, 10 = 4, 9 = 3
and for 5, 11, 23 = 2 (same number of factors
therefore sorted in increasing order of index)

Input : {104, 210, 315, 166, 441, 180}
Output : 180 210 315 441 104 166


 


The following steps sort numbers in decreasing order of count of factors. 

  1. Count distinct number of factors of each element. Refer this.
  2. You can use a structure for each element to store its original index and count of factors. Create an array of such structures to store such information for all the elements.
  3. Sort this array of structures on the basis of the problem statement using any sorting algorithm.
  4. Traverse this array of structures from the beginning and get the number from the original array with the help of the index stored in the structure of each element of the sorted array of structures.

Output: 
 

20 16 10 9 5 11 23


Time Complexity: O(n ?n)
Auxiliary Space: O(n)


 

Comment
Article Tags:
Article Tags: