I am learning C and came over the topic of sorting. I wrote a comp()
function in and used qsort
to sort an array of int
. Now for the next task I need to remove the duplicates from the array.
Is it possible to sort and remove duplicates at the same time?
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int indexes[10] = { 0, 98, 45, 65, 45, 98, 78, 56, 65, 45 };
int comp(const void * elem1, const void * elem2) {
int f = *((int*) elem1);
int s = *((int*) elem2);
if (f > s) {
return 1;
}
if (f < s) {
return -1;
}
return 0;
}
void printIndexArray() {
int i = 0;
for (i = 0; i < 10; i++) {
printf("i is %d\n", indexes[i]);
}
}
int main() {
qsort(indexes, sizeof(indexes) / sizeof(int), sizeof(int), comp);
printIndexArray();
return 0;
}
Since your numbers are already sorted, removing dupes is easy. In C++, it's even built in as std::unique
:
http://en.cppreference.com/w/cpp/algorithm/unique
Assuming you want to do it yourself, you can do it the same way unique
does it:
int* unique (int* first, int* last)
{
if (first==last) return last;
int* result = first;
while (++first != last)
{
if (!(*result == *first))
*(++result)=*first;
}
return ++result;
}
Yes
This can be achieved by mergesort. If both left and right are the same just merge the one value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With