Question: Write a Java program that gets a one - dimensional integer array and return the count of unique elements in the array. You will write
Write a Java program that gets a onedimensional integer array and return the count of unique elements in the array. You will write a method numUnique that takes in the array and returns the count.
For example,
Enter the number of elements you want to store: Enter the elements of the array: Original array length: Array elements are: The number of unique elements is:
One way to find similar elements would be to use nested loops andor multiple arrays. But there's a nifty trick we can use: sort the array and then check for adjacent elements. For example, in the example above the original array is:
Sorted, this array will be:
Now we can compare elements next to each other. Let's start with arrayi where i is our first unique value ie the value If its successor, arrayi is the same, then we wouldn't count it since it's not unique. We'd continue this process of comparing adjacent values until we've processed the entire array.
Great, but sorting?? No problem! Use Arrays import java.util.Arraysthat class we used before with its toString method. Look up how to use its sort method.
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
