In: Computer Science
Suppose you are provided with an array of integer values. Write
pseudocode for a program to determine how many unique values are in
the array. Your solution should require time that is linearithmic
in the size of the array.
(For example, if the array contains the values {1,3,4,1,2}, the
answer is "4", because the array contains the values 1, 2, 3, and
4)
Here I am providing the answer for the above question:
public class UniqueCount
{
void countUnique(int a[], int size)
{
int count=0;
for (int i = 0; i < size; i++)
{
int j;
for (j = 0; j < i; j++) //each elements is compared
with current element a[i].
if (a[i] == a[j]) //if any match
occur we will break the loop
break;
if (i == j) //if no match occur in the particular
iteration the i,j values will be same.
{
count++; //so now increase the
count.
}
}
System.out.println("\nCount of Unique
Values:"+count);
}
public static void main (String[] args)
{
UniqueCount c=new
UniqueCount();
int a[] = {1,3,4,1,2,5,2,7,3,9,8,12,45,76};
int size = a.length;
c.countUnique(a, size);
}
}
Output:
Hoping that the above code will help you...Thank you...