Tuesday, 26 July 2011

Finding Repeated Element

Find an integer that repeats more than (>)n/2 times in a given array of size n in O(1) time complexity.? Give an efficient Algorithm?
Note: The array is not sorted.


Algorithm:Let num=1st elt of array...freq=1...then for each elt e remaining if e==num increment freq else decrement..if freq becomes 0 then make num=e and freq as 1...at last num will hold the required  number.


Program Coding:


#include<stdio.h>
#include<conio.h>


void main()
{
int a[]={5,1,5,2,5,3,5,4,5,3};
int len;
len=sizeof(a)/sizeof(int);
int n,f=1,i;
n=a[0];
clrscr();
for(i=1;i<len;i++)
{
if(f==0)
{
n=a[i];
f=1;
}


if(a[i]==n)
f++;
else
f--;
}
printf("%d",n);
getch();
}

No comments:

Post a Comment