Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,907 questions

51,839 answers

573 users

How to remove duplicate elements from int array using qsort in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
 
int compare(const void *a, const void *b) {
   return ( *(int*)a - *(int*)b );
}
 
int remove_duplicates(int *p, int len) {
	qsort(p, len, sizeof(int), compare);
	
	int j;
	for (int i = j = 0; i < len; i++)
		if (p[i] != p[j]) p[++j] = p[i];
		
	return j + 1;
}
 
int main()
{
	int arr[] = {2, 3, 2, 6, 3, 7, 9, 9};
	
	int len = remove_duplicates(arr, sizeof(arr) / sizeof(arr[0]));
	
	for (int i = 0; i < len; i++) 
	    printf("%d ", arr[i]);
 
	return 0;
}
 

 
/*
run:
 
2 3 6 7 9 
 
*/

 



answered Sep 27, 2020 by avibootz

Related questions

1 answer 180 views
1 answer 306 views
1 answer 164 views
1 answer 151 views
1 answer 163 views
1 answer 279 views
...