Compress Array by Extracting Unique elements of an array in C on Linux Platform

   C Linux Code to extract the unique numbers only.
   0. assign the first elt to result array
   1.Traverse through the array
   2.compare first to next and if not equal the copy to the resultant array
   if input array is
   int arr[]={1,1,2,2,2,3,4,5,5};
   then output array should be
   1 2 3 4 5

#include<stdio.h>
#include<stdlib.h>

int* zeroshift(int *, int);
int main()
{
    int size,i,j;
    int arr[]={1,1,2,2,2,3,4,5,5};
    size=sizeof(arr)/sizeof(int);
    int* ptr=zeroshift(arr,size);
    printf("After after elemenating the repeated elements, array is:\n");
    for(i=0;i<size;i++)
        printf("%d ",ptr[i]);
    printf("\n");
    return 0;
}

int* zeroshift(int *arr,int size)
{
    int i;
    int count=0;
    int *result=(int *)malloc(size*sizeof(int));
    result[count++]=arr[0];
    for(i=0;i<size-1;i++)/* 1.Traverse through the array*/
    {
        if(arr[i]!=arr[i+1])
        {
            result[count]=arr[i+1];/*2.copy the non equal elts to new array say result and increment the count*/
            count++;
        }

    }
    return result;
}
/*
   1 2 3 4 5
 */

No comments:

Post a Comment