Wednesday, 8 May 2013

Sort elements by frequency

Given an array of integers, sort the array according to frequency of elements. For example, if the input array is {2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12}, then modify the array to {3, 3, 3, 3, 2, 2, 2, 12, 12, 4, 5}.

**************************************
*         C++ implementation:        *
**************************************
#include<iostream>
#include<stdlib.h>
using namespace std;
struct tree
{
int freq,info;
struct tree *lchild,*rchild;
};
typedef struct tree* TREE;
TREE creat(TREE,int);
void sort();
void inorder(TREE);

int e[20],c[20],l=0;

int main()
{
cout<<"Enter the number of elements to be inserted:";
int n;cin>>n;
TREE root=NULL;

cout<<"Enter the elements:";
for(int i=0;i<n;i++)
{
  int ele;cin>>ele;
  root=creat(root,ele);
}

inorder(root);
sort();
cout<<"Sorted elements:";
for(int i=0;i<=l;i++)
{
  for(int j=0;j<c[i];j++)
  cout<<e[i]<<"\t";
}
cout<<endl;
return(0);
}


void inorder(TREE root)
{
  if(root!=NULL)
  {
    inorder(root->lchild);
    e[++l]=root->info;
    c[l]=root->freq;
    inorder(root->rchild);
  }
}

void sort()
{
int temp;
for(int i=0;i<l-1;i++)
for(int j=0;j<l-i-1;j++)
{
  if(c[j]<c[j+1])
   {
      temp=c[j];
      c[j]=c[j+1];
      c[j+1]=temp;
      temp=e[j];
      e[j]=e[j+1];
      e[j+1]=temp;
   }
}

}

TREE creat(TREE node,int key)
{
TREE nnode,x,p;
nnode=(TREE)malloc(sizeof(struct tree));
nnode->lchild=NULL;
nnode->rchild=NULL;
nnode->info=key;
nnode->freq=1;

if(node==NULL)
return(nnode);

x=node;
while(x!=NULL)
{
   p=x;
   if(key>x->info)
   x=x->rchild;
   else if(key<x->info)
   x=x->lchild;
   else
   {
        x->freq++;
        return(node);
   }
}
if(key>p->info)
p->rchild=nnode;
else
p->lchild=nnode;
return(node);
}    

No comments:

Post a Comment