I want to detect duplicates in a given array using divide and conquer approach. Can I use Merge Sort for this:
First split the array in log N steps
Then sort by merging
While merging use a counter variable to detect duplicates. O(N)
So in total it will take O(N log N) steps...
Is this approach correct?
You just use merge sort to sort the array which takes O(nlogn) , once the array is sorted
you can detect duplicates in O(n) time so total time is O(nlogn).
For example the array is arr[]
and it has N
elements.
1.Sort array using merge sort.
2. (a)variables
start -- initially at position 1 of array (arr has elements from 1 to N).
count--- to count number of times a specific number occurs
(b)method
for(i=2;i<=N;i++)
{
if(arr[i]!=arr[start])
{
printf("%d has occurred %d times",arr[start],count);
count=1;
start=i;
}
else count++;
}
printf("%d has occurred %d times",arr[start],count);
Thuis total time O(nlogn) space O(n).