Print All the Repeated Numbers with Frequency in an Array

Given an array, Print All the Repeated Numbers with Frequency in an Array


For example:

If the input is 
1 1 1 1 2 2 2 3 3 4

then the result is 

1 4
2 3
3 2
4 1

Implementation:


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* swap function that swaps the values using call by reference */
void swap(int *x,int *y)
{
 int temp;
 temp=*x;
 *x=*y;
 *y=temp;
}

int main(void) {
 int a[]={1,2,3,4,1,2,3,1,2,1},i,j,temp,count;
 
 /* calculate te size of the array or number of elements of the array */
 int n=sizeof(a)/sizeof(*a);
 
 /* Sort the array */
 for(i=0;i<n;i++)
 {
  for(j=i+1;j<n;j++)
  {
   if(*(a+i)>*(a+j))
   swap((a+i),(a+j));
  }
 }
 
 /* Print the array */
 for(i=0;i<n;i++)
  printf("%d ",*(a+i));
 printf("\n");
 
 /* Find each element's frequency and print it */
 temp=*(a+i);
 count=1;
 for(i=1;i<=n;i++)
 {
  if(*(a+i)==temp)
  count++;
  else
  {
   printf("%d %d\n",temp,count);
   count=1;
   temp=*(a+i);
  }
 }
 return 0;
}