Sort on the basis of number of factors using STL
Last Updated :
16 Mar, 2023
Given an array of positive integers. Sort the given array in decreasing order of a number of factors of each element, i.e., an element having the highest number of factors should be the first to be displayed and the number having the least number of factors should be the last one. Two elements with an 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
We have already discussed a structure-based solution to sort according to a number of factors. The following steps sort numbers in decreasing order of count of factors.
- Count a distinct number of factors of each element. Refer this.
- Create a vector of pairs that stores elements and their factor counts.
- Sort this array based on the problem statement using any sorting algorithm.
Implementation:
CPP
// Sort an array of numbers according
// to number of factors.
#include <bits/stdc++.h>
using namespace std;
// Function that helps to sort elements
// in descending order
bool compare(const pair<int, int> &a,
const pair<int, int> &b) {
return (a.first > b.first);
}
// Prints array elements sorted in descending
// order of number of factors.
void printSorted(int arr[], int n) {
vector<pair<int, int>> v;
for (int i = 0; i < n; i++) {
// Count factors of arr[i].
int count = 0;
for (int j = 1; j * j <= arr[i]; j++) {
// To check Given Number is Exactly
// divisible
if (arr[i] % j == 0) {
count++;
// To check Given number is perfect
// square
if (arr[i] / j != j)
count++;
}
}
// Insert factor count and array element
v.push_back(make_pair(count, arr[i]));
}
// Sort the vector
sort(v.begin(), v.end(), compare);
// Print the vector
for (int i = 0; i < v.size(); i++)
cout << v[i].second << " ";
}
// Driver's Function
int main() {
int arr[] = {5, 11, 10, 20, 9, 16, 23};
int n = sizeof(arr) / sizeof(arr[0]);
printSorted(arr, n);
return 0;
}
Java
// java program to Sort on the basis of
// number of factors using STL
import java.io.*;
import java.util.*;
class Pair
{
int a;
int b;
Pair(int a, int b)
{
this.a=a;
this.b=b;
}
}
// creates the comparator for comparing first element
class SComparator implements Comparator<Pair> {
// override the compare() method
public int compare(Pair o1, Pair o2)
{
if (o1.a == o2.a) {
return 0;
}
else if (o1.a < o2.a) {
return 1;
}
else {
return -1;
}
}
}
class GFG {
// Function to find maximum partitions.
static void printSorted(int arr[], int n)
{
ArrayList<Pair> v = new ArrayList<Pair>();
for (int i = 0; i < n; i++) {
// Count factors of arr[i].
int count = 0;
for (int j = 1; j * j <= arr[i]; j++) {
// To check Given Number is Exactly
// divisible
if (arr[i] % j == 0) {
count++;
// To check Given number is perfect
// square
if (arr[i] / j != j)
count++;
}
}
// Insert factor count and array element
v.add(new Pair (count, arr[i]));
}
// Sort the vector
// Sorting the arraylist elements in descending order
Collections.sort(v, new SComparator());
// Print the vector
for (Pair i : v)
System.out.print(i.b+" ");
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 5, 11, 10, 20, 9, 16, 23 };
int n = arr.length;
printSorted(arr, n);
}
}
// This code is contributed by Aarti_Rathi
Python3
# python program to Sort on the basis of
# number of factors using STL
from functools import cmp_to_key
# creates the comparator for comparing first element
def compare(a, b):
return b[0] - a[0]
# Function to find maximum partitions.
def printSorted(arr,n):
v =[]
for i in range(n):
count=0
j=1
# Count factors of arr[i].
while(j*j<=arr[i]):
# To check Given Number is Exactly
# divisible
if(arr[i]%j ==0):
count+=1
# To check Given number is perfect
# square
if(arr[i]/j!=j):
count+=1
j+=1
# Insert factor count and array element
v.append((count,arr[i]))
# Sort the vector
# Sorting the arraylist elements in descending order
v=sorted(v, key=cmp_to_key(compare))
# Print the vector
for a,b in v:
print(b,end=" ")
# Driver Code
arr = [5, 11, 10, 20, 9, 16, 23]
n = len(arr)
printSorted(arr, n)
# This code is contributed by Aarti_Rathi
C#
// C# program to Sort on the basis of
// number of factors using STL
using System;
using System.Collections.Generic;
// Class Pair
class Pair
{
public int a;
public int b;
public Pair(int a, int b)
{
this.a = a;
this.b = b;
}
}
// creates the comparator for comparing first element
class SComparator : IComparer<Pair>
{
// override the compare() method
public int Compare(Pair o1, Pair o2)
{
if (o1.a == o2.a)
{
return 0;
}
else if (o1.a < o2.a)
{
return 1;
}
else
{
return -1;
}
}
}
public class GFG{
// Function to find maximum partitions.
static void printSorted(int[] arr, int n)
{
List<Pair> v = new List<Pair>();
for (int i = 0; i < n; i++)
{
// Count factors of arr[i].
int count = 0;
for (int j = 1; j * j <= arr[i]; j++)
{
// To check Given Number is Exactly
// divisible
if (arr[i] % j == 0)
{
count++;
// To check Given number is perfect
// square
if (arr[i] / j != j)
count++;
}
}
// Insert factor count and array element
v.Add(new Pair (count, arr[i]));
}
// Sort the vector
// Sorting the list elements in descending order
v.Sort(new SComparator());
// Print the vector
foreach (Pair i in v)
Console.Write(i.b + " ");
}
// Driver code
static public void Main (){
int[] arr = { 5, 11, 10, 20, 9, 16, 23 };
int n = arr.Length;
printSorted(arr, n);
}
}
// This code is contributed by akashish__
JavaScript
// creates the comparator for comparing first element
function compare(a, b) {
return b[0] - a[0];
}
// Function to find maximum partitions.
function printSorted(arr) {
const n = arr.length;
const v = [];
for (let i = 0; i < n; i++) {
let count = 0;
let j = 1;
// Count factors of arr[i].
while (j * j <= arr[i])
{
// To check Given Number is Exactly divisible
if (arr[i] % j == 0) {
count++;
// To check Given number is perfect square
if (arr[i] / j != j) count++;
}
j++;
}
// Insert factor count and array element
v.push([count, arr[i]]);
}
// Sort the vector
// Sorting the arraylist elements in descending order
v.sort(compare);
// Print the vector
v.forEach((i) => console.log(i[1]));
}
// Driver Code
const arr = [5, 11, 10, 20, 9, 16, 23];
printSorted(arr);
// This code is contributed by Shivhack999
Output:20 16 10 9 5 11 23
Time Complexity: O(n*log(n))
Auxiliary Complexity: O(n)
Similar Reads
Sort elements on the basis of number of factors 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 num
10 min read
Sum of Factors of a Number using Prime Factorization Given a number N. The task is to find the sum of all factors of the given number N. Examples: Input : N = 12 Output : 28 All factors of 12 are: 1,2,3,4,6,12 Input : 60 Output : 168 Approach: Suppose N = 1100, the idea is to first find the prime factorization of the given number N. Therefore, the pri
13 min read
How to sort an Array using STL in C++? Given an array arr[], sort this array using STL in C++. Example: Input: arr[] = {1, 45, 54, 71, 76, 12} Output: {1, 12, 45, 54, 71, 76} Input: arr[] = {1, 7, 5, 4, 6, 12} Output: {1, 4, 5, 6, 7, 12} Approach: Sorting can be done with the help of sort() function provided in STL. Syntax: sort(arr, arr
1 min read
Sort the Matrix based on the given column number Given a Matrix of size M * N (0-indexed) and an integer K, the matrix contains distinct integers only, the task is to sort the Matrix (i.e., the rows of the matrix) by their Values in the Kth column, from Maximum to Minimum. Return the matrix after sorting it. Examples: Input: Matrix = [[10, 6, 9, 1
12 min read
Insertion sort using C++ STL Implementation of Insertion Sort using STL functions. Pre-requisites : Insertion Sort, std::rotate, std::upper_bound, C++ Iterators. The idea is to use std::upper_bound to find an element making the array unsorted. Then we can rotate the unsorted part so that it ends up sorted. We can traverse the a
1 min read
Efficient program to print the number of factors of n numbers Given an array of integers. We are required to write a program to print the number of factors of every element of the given array.Examples: Input: 10 12 14 Output: 4 6 4 Explanation: There are 4 factors of 10 (1, 2, 5, 10) and 6 of 12 and 4 of 14. Input: 100 1000 10000 Output: 9 16 25 Explanation: T
15 min read