Question Name:Counting Sort

#include<stdio.h>
#include<stdlib.h>
struct node{
  int data;
  int freq;
  struct node* next;
};
void swap(int *xp, int *yp) 
{ 
    int temp = *xp; 
    *xp = *yp; 
    *yp = temp; 
} 
void bubblesort(int arr[], int n) 
{ 
   int i, j; 
   for (i = 0; i < n-1; i++)       
     
       for (j = 0; j < n-i-1; j++)  
           if (arr[j] > arr[j+1]) 
              swap(&arr[j], &arr[j+1]); 
}
struct node* createnode(){
  struct node* temp;
  temp=(struct node*)malloc(sizeof(struct node));
  temp->freq=1;
  temp->next=NULL;
  return temp;
}
void printl(struct node* ptr){
  while(ptr!=NULL){
    printf("%d %d\n",ptr->data,ptr->freq);
    ptr=ptr->next;
  }
}
int checkoccur(struct node* ptr, int n){
  while(ptr!=NULL){
    if(n==ptr->data){
      (ptr->freq)++;
      return 1;
    }
    ptr=ptr->next;
  }
  return 0;
}
int main() {
  int j;  
    int n;
    scanf("%d",&n);
    int arr[n];
    for(j=0;j<n;j++)
      scanf("%d",&arr[j]);
  bubblesort(arr,n);
    struct node* head=createnode();
    struct node* ptr=head;
    head->data=arr[0];
    for(j=1;j<n;j++){
      if(checkoccur(head,arr[j])==0){
        ptr->next=createnode();
        ptr=ptr->next;
        ptr->data=arr[j];
      }
    }
    printl(head);
    free(head);
	return 0;
}

Problem Description

You have been given an integer array A of size N. Each element of the array ranges between 1 and 10^5. You need to find the frequency of each distinct element of the array. The elements need to be present in the output in ascending order. You need to print the value and then frequency of each distinct element.

Input Format:

The first line contains a single integer N denoting the size of the array. The next line contains N space separated integers, denoting the elements of the array.

Output Format

For each distinct integer, print its value and then frequency in a new line. The distinct integers should appear in the output in ascending order.

Constraints

1<=N<=100
1<=A[i]<=100

  • Test Case 1

    Input (stdin)

    5
    5 4 3 2 1
    

    Expected Output

    1 1
    2 1
    3 1
    4 1
    5 1
  • Test Case 2

    Input (stdin)

    10
    5 6 21 75 5 6 2 21 21 21 
    

    Expected Output

    2 1
    5 2
    6 2
    21 4
    75 1

Leave a Reply

Your email address will not be published. Required fields are marked *

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
CHP Adblock Detector Plugin | Codehelppro