944,103 Members | Top Members by Rank

Ad:
  • C Code Snippet
  • Views: 7372
  • C RSS
0

Efficient code for extracting unique elements from sorted array.

by on May 24th, 2006
Efficient code for extracting unique elements from sorted array.

Time Complexity is O(n)
C Code Snippet (Toggle Plain Text)
  1. #include<stdio.h>
  2. main()
  3. {
  4. int i,a[20],n,t,j,k;
  5. printf("\n Enter the number of elements in sorted list");
  6. scanf("%d",&n);
  7. printf("\n enter the sorted numbers with duplicates");
  8. for(i=1;i<=n;i++)
  9. scanf("%d",&a[i]);
  10. for(i=1;i<=n;i++)
  11. t+=a[i];
  12. for(i=1,k=1,j=i+1;j<=n;j++)
  13. {
  14. if(t-a[i]==t-a[j])
  15. continue;
  16. k++;
  17. a[k]=a[j];
  18. i=j;
  19. }
  20. printf("\n Array after removing the duplicates");
  21. for(i=1;i<=k;i++)
  22. printf(" %d",a[i]);
  23. }
Comments on this Code Snippet
May 5th, 2010
0

Here is a much simple solution

  1. // this program takes a sorted array as input and prints the unique numbers in that array as the output
  2. // time complexity is of the order n and also checks whether the array //is sorted or not
  3. #include<stdio.h>
  4.  
  5. void main(char* argv)
  6. {
  7. int a[100],b[100];
  8. int i=0,j=0,k=0,n=0;
  9. int flag=0;
  10. printf("Enter number of elements in the array \n");
  11. scanf("%d",&n);
  12. printf("Enter all the %d elements \n",n);
  13. for(i=0;i<n;i++)
  14. scanf("%d",&a[i]);
  15. // to check whether if the array is sorted or not
  16. for(i=0;i<n;i++)
  17. if(!(a[i]<=a[i+1]))
  18. flag=1;
  19. if(flag==1)
  20. printf("The given array is not sorted \n");
  21. else
  22. {
  23. for(i=0,j=i+1;j<=n;j++)
  24. {
  25. if(a[i]==a[j]) // we compare if a[i] and a[j] are equal or not if equal then contiue
  26. continue;
  27. b[k++]=a[i];// if they are not equal then b[k++] is equal to the repeating value
  28. i=j; // assign i==j to start from the end of the repeating elemnet
  29. }
  30. printf("The Unique numbers in the array are \n");
  31. for(i=0;i<k;i++)
  32. printf("%d \n",b[i]);
  33. }
  34. }
Last edited by Nick Evan; May 6th, 2010 at 3:38 am. Reason: Fixed code-tags. Please put the code BETWEEN the two tags
Newbie Poster
raghuram1987 is offline Offline
6 posts
since Apr 2009
May 5th, 2010
0

Re: Efficient code for extracting unique elements from sorted array.

If you want to have them in the same array insted of b[k++] use a[k++] and print till i<k;
Newbie Poster
raghuram1987 is offline Offline
6 posts
since Apr 2009
Message:
Previous Thread in C Forum Timeline: queue functions not working right.
Next Thread in C Forum Timeline: unique random pair





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC