Print numbers in descending order along with their frequencies

Given an array of integer elements, the task is to arrange the elements in descending order and find their frequencies. This approach works when the input array is already sorted in ascending order.

Input : arr[]={1,1,1,2,2,2,3,3,4,5,6,7,7}
Output : 7 occurs: 2
         6 occurs: 1
         5 occurs: 1
         4 occurs: 1
         3 occurs: 2
         2 occurs: 3
         1 occurs: 3

Syntax

// For counting frequency while traversing backwards
for(i = size-1; i > 0; i--) {
    if(arr[i] != arr[i-1]) {
        frequency = current_end - i;
        // Print element and frequency
    }
}

Algorithm

START
Step 1 ? Input array with elements in sorted order
Step 2 ? Calculate size of array using sizeof(arr)/sizeof(arr[0])
Step 3 ? Initialize end pointer to array size
Step 4 ? Loop from i=size-1 down to i>0
         IF arr[i] != arr[i-1]
             frequency = end - i
             Print arr[i] and frequency
             Update end = i
         END IF
Step 5 ? Print arr[0] and its frequency
STOP

Example

This example demonstrates counting frequencies by traversing the sorted array from right to left −

#include <stdio.h>

int main() {
    int a[] = {1,1,1,2,2,2,3,3,4,5,6,7,7};
    int siz, i, en, to;
    
    siz = sizeof(a)/sizeof(a[0]);
    en = siz;
    
    for(i = siz-1; i > 0; i--) {
        if(a[i] != a[i-1]) {
            to = en - i;
            printf("%d occurs: %d<br>", a[i], to);
            en = i;
        }
    }
    
    to = en;
    printf("%d occurs: %d<br>", a[0], to);
    
    return 0;
}
7 occurs: 2
6 occurs: 1
5 occurs: 1
4 occurs: 1
3 occurs: 2
2 occurs: 3
1 occurs: 3

How It Works

  • The algorithm traverses the sorted array from right to left
  • When it encounters a different element, it calculates the frequency using end - current_position
  • The en variable keeps track of the end position of the current group of identical elements
  • Elements are printed in descending order naturally due to backward traversal

Key Points

  • This method requires the input array to be sorted in ascending order
  • Time complexity is O(n) for traversing the array once
  • Space complexity is O(1) as no extra storage is used

Conclusion

This approach efficiently prints unique elements in descending order along with their frequencies by traversing a pre-sorted array backwards. It's optimal for sorted input with linear time complexity.

Updated on: 2026-03-15T11:05:30+05:30

595 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements