Your sorting algorithm has complexity O(n^2)
. For an input with size 10^5
it takes many magnitude more than O(nlogn)
quick sort algorithm.
Here you can use qsort()
to solve the problem.
qsort(a, b, sizeof int, cmp);
Where cmp
is
int cmp(const void *a, const void *b)
{
return (*(int *) a - *(int *) b);
}
The algorithm after sorting is much more simpler.
int p = a[0], ct=0;
for(size_t i = 1; i<=b-1; i++)
{
if( a[i] == a[i-1])
ct++;
else{
if( ct > 1){
// a[i-1] should be printed.
}
ct = 1;
}
}
if( ct > 1){
//a[b-1] should also be print.
}
The idea is something like this
As the numbers are sorted we will get a monotonic sequence.
We compare every number with one that came before. If there is duplicate they will appear next to next.
We only collect those numbers which appear multiple times.
Also there are few things you can follow
Declaring large variables inside a method sometimes is constrained by the available memory(automatic storage duration).(may have stackoverflow etc) Make it global.(something of static storage duration).
The variable names are not a bit readable
.
You can get help in case of using a sorting algorithm.
Knowing the complexity of different algorithms helps. The thing is in your case the complexity is O(n^2). The sorting algorithm better than this is the popular merge sort etc. This simple idea solves the problem in your case.
You can check yourself that this code is atleast a bit more readable than your version. This helps avoid small mistakes.
int temp = a[0], count=0;
for(size_t i = 1; i<=len-1; i++)
{
if( arr[i] == arr[i-1])
count++;
else{
if( count > 1){
// a[i-1] should be printed.
}
count = 1;
}
}
if( count > 1){
//arr[len-1] should also be print.
}