📜  按频率降序对数组元素进行排序

📅  最后修改于: 2021-04-29 03:28:54             🧑  作者: Mango

给定N个整数的数组arr [] 。任务是根据元素的频率以降序对数组arr []进行排序。
注意:如果两个元素的频率相同,则较小的元素应首先出现。
例子:

方法:

  • 将所有元素的频率存储在数组arr []中
  • 对于arr [] = {4,4,5,6,4,2,2,8,5}
    上述阵列的频率阵列为:
    freq [] = {0,0,2,0,3,2,0,1,0,1}
  • 遍历频率数组,并对所有频率大于1的元素,将数组arr []中的值更新为:
  • 以降序对数组arr []进行排序。
  • 遍历数组arr []并按照步骤2中数组元素的更新获取该元素的元素和频率,请执行以下操作:

例如:

  • 对于arr []中的每个元素,找到每个索引处的和频率(例如f ),然后将值f打印多次。

下面是上述方法的实现:

C++
// C++ program to sort an array in
// decreasing order of their frequnecy
#include "bits/stdc++.h"
using namespace std;
 
// Function that return the index
// upto all the array elements are
// updated.
int sortByFreq(int* arr, int n)
{
 
    // Initialise maxE = -1
    int maxE = -1;
 
    // Find the maximum element of
    // arr[]
    for (int i = 0; i < n; i++) {
        maxE = max(maxE, arr[i]);
    }
 
    // Create frequency array freq[]
    int freq[maxE + 1] = { 0 };
 
    // Update the frequency array as
    // per the occurence of element in
    // arr[]
    for (int i = 0; i < n; i++) {
        freq[arr[i]]++;
    }
 
    // Initialise cnt to 0
    int cnt = 0;
 
    // Traversing freq[]
    for (int i = 0; i <= maxE; i++) {
 
        // If freq of an element is
        // greater than 0 update the
        // value of arr[] at index cnt
        // & increment cnt
        if (freq[i] > 0) {
 
            int value = 100000 - i;
            arr[cnt] = 100000 * freq[i] + value;
            cnt++;
        }
    }
 
    // Return cnt
    return cnt;
}
 
// Function that print array arr[]
// elements in sorted order
void printSortedArray(int* arr, int cnt)
{
 
    // Traversing arr[] till index cnt
    for (int i = 0; i < cnt; i++) {
 
        // Find frequency of elements
        int frequency = arr[i] / 100000;
 
        // Find value at index i
        int value = 100000 - (arr[i] % 100000);
 
        // Traversing till frequency
        // to print value at index i
        for (int j = 0; j < frequency; j++) {
            cout << value << ' ';
        }
    }
}
 
// Driver code
int main()
{
 
    int arr[] = { 4, 4, 5, 6, 4, 2, 2, 8, 5 };
 
    // Size of array arr[]
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function call to get cnt
    int cnt = sortByFreq(arr, n);
 
    // Sort the arr[] in decreasing order
    sort(arr, arr + cnt, greater());
 
    // Function that prints elements
    // in decreasing order
    printSortedArray(arr, cnt);
 
    return 0;
}


Java
// Java program to sort an array in
// decreasing order of their frequnecy
import java.util.*;
 
class GFG{
  
// Function that return the index
// upto all the array elements are
// updated.
static int sortByFreq(Integer []arr, int n)
{
  
    // Initialise maxE = -1
    int maxE = -1;
  
    // Find the maximum element of
    // arr[]
    for (int i = 0; i < n; i++) {
        maxE = Math.max(maxE, arr[i]);
    }
  
    // Create frequency array freq[]
    int freq[] = new int[maxE + 1];
  
    // Update the frequency array as
    // per the occurence of element in
    // arr[]
    for (int i = 0; i < n; i++) {
        freq[arr[i]]++;
    }
  
    // Initialise cnt to 0
    int cnt = 0;
  
    // Traversing freq[]
    for (int i = 0; i <= maxE; i++) {
  
        // If freq of an element is
        // greater than 0 update the
        // value of arr[] at index cnt
        // & increment cnt
        if (freq[i] > 0) {
  
            int value = 100000 - i;
            arr[cnt] = 100000 * freq[i] + value;
            cnt++;
        }
    }
  
    // Return cnt
    return cnt;
}
  
// Function that print array arr[]
// elements in sorted order
static void printSortedArray(Integer []arr, int cnt)
{
  
    // Traversing arr[] till index cnt
    for (int i = 0; i < cnt; i++) {
  
        // Find frequency of elements
        int frequency = arr[i] / 100000;
  
        // Find value at index i
        int value = 100000 - (arr[i] % 100000);
  
        // Traversing till frequency
        // to print value at index i
        for (int j = 0; j < frequency; j++) {
            System.out.print(value + " ");
        }
    }
}
  
// Driver code
public static void main(String[] args)
{
  
    Integer arr[] = { 4, 4, 5, 6, 4, 2, 2, 8, 5 };
  
    // Size of array arr[]
    int n = arr.length;
  
    // Function call to get cnt
    int cnt = sortByFreq(arr, n);
  
    // Sort the arr[] in decreasing order
    Arrays.sort(arr, Collections.reverseOrder());
  
    // Function that prints elements
    // in decreasing order
    printSortedArray(arr, cnt);
  
}
}
 
// This code is contributed by sapnasingh4991


Python3
# Python program to sort an array in
# decreasing order of their frequnecy
 
# Function that return the index
# upto all the array elements are
# updated.
def sortByFreq(arr, n):
 
    # Initialise maxE = -1
    maxE = -1;
 
    # Find the maximum element of
    # arr[]
    for i in range(n):
        maxE = max(maxE, arr[i])
 
    # Create frequency array freq[]
    freq = [0]*(maxE + 1);
 
    # Update the frequency array as
    # per the occurence of element in
    # arr[]
    for i in range(n):
        freq[arr[i]] += 1;
     
    # Initialise cnt to 0
    cnt = 0;
 
    # Traversing freq[]
    for i in range(maxE+1):
 
        # If freq of an element is
        # greater than 0 update the
        # value of arr[] at index cnt
        # & increment cnt
        if (freq[i] > 0):
 
            value = 100000 - i;
            arr[cnt] = 100000 * freq[i] + value;
            cnt += 1;
         
    # Return cnt
    return cnt;
 
# Function that print array arr[]
# elements in sorted order
def printSortedArray(arr, cnt):
 
    # Traversing arr[] till index cnt
    for i in range(cnt):
 
        # Find frequency of elements
        frequency = arr[i] / 100000;
 
        # Find value at index i
        value = 100000 - (arr[i] % 100000);
 
        # Traversing till frequency
        # to print value at index i
        for j in range(int(frequency)):
            print(value, end=" ")
             
# Driver code
if __name__=='__main__':
 
    arr = [ 4, 4, 5, 6, 4, 2, 2, 8, 5 ]
 
    # Size of array arr[]
    n = len(arr)
 
    # Function call to get cnt
    cnt = sortByFreq(arr, n);
 
    # Sort the arr[] in decreasing order
    arr.sort(reverse = True)
 
    # Function that prints elements
    # in decreasing order
    printSortedArray(arr, cnt);
 
# This code is contributed by Princi Singh


C#
// C# program to sort an array in
// decreasing order of their frequnecy
using System;
 
class GFG {
 
  // Function that return the index
  // upto all the array elements are
  // updated.
  static int sortByFreq(int[] arr, int n)
  {
 
    // Initialise maxE = -1
    int maxE = -1;
 
    // Find the maximum element of
    // arr[]
    for (int i = 0; i < n; i++)
    {
      maxE = Math.Max(maxE, arr[i]);
    }
 
    // Create frequency array freq[]
    int[] freq = new int[maxE + 1];
 
    // Update the frequency array as
    // per the occurence of element in
    // arr[]
    for (int i = 0; i < n; i++)
    {
      freq[arr[i]]++;
    }
 
    // Initialise cnt to 0
    int cnt = 0;
 
    // Traversing freq[]
    for (int i = 0; i <= maxE; i++)
    {
 
      // If freq of an element is
      // greater than 0 update the
      // value of arr[] at index cnt
      // & increment cnt
      if (freq[i] > 0)
      {
        int value = 100000 - i;
        arr[cnt] = 100000 * freq[i] + value;
        cnt++;
      }
    }
 
    // Return cnt
    return cnt;
  }
 
  // Function that print array arr[]
  // elements in sorted order
  static void printSortedArray(int[] arr, int cnt)
  {
 
    // Traversing arr[] till index cnt
    for (int i = 0; i < cnt; i++)
    {
 
      // Find frequency of elements
      int frequency = arr[i] / 100000;
 
      // Find value at index i
      int value = 100000 - (arr[i] % 100000);
 
      // Traversing till frequency
      // to print value at index i
      for (int j = 0; j < frequency; j++)
      {
        Console.Write(value + " ");
      }
    }
  }
 
  // Driver code
  public static void Main()
  {
    int[] arr = { 4, 4, 5, 6, 4, 2, 2, 8, 5 };
 
    // Size of array arr[]
    int n = arr.Length;
 
    // Function call to get cnt
    int cnt = sortByFreq(arr, n);
 
    // Sort the arr[] in decreasing order
    Array.Sort(arr);
    Array.Reverse(arr);
 
    // Function that prints elements
    // in decreasing order
    printSortedArray(arr, cnt);
  }
}
 
// This code is contributed by subhamahato348


输出:
4 4 4 2 2 5 5 6 8

时间复杂度: O(N * log N)
辅助空间: O(N)