Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort and remove duplicates from int array in c

Tags:

arrays

c

sorting

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;
}
like image 292
user2800463 Avatar asked Sep 20 '13 19:09

user2800463


2 Answers

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;
}
like image 113
StilesCrisis Avatar answered Oct 31 '22 01:10

StilesCrisis


Yes

This can be achieved by mergesort. If both left and right are the same just merge the one value

like image 44
Ed Heal Avatar answered Oct 31 '22 01:10

Ed Heal