Efficient code for extracting unique elements from sorted array.

Time Complexity is O(n)

``````#include<stdio.h>
main()
{
int i,a[20],n,t,j,k;
printf("\n Enter the number of elements in sorted list");
scanf("%d",&n);
printf("\n enter the sorted numbers with duplicates");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
for(i=1;i<=n;i++)
t+=a[i];
for(i=1,k=1,j=i+1;j<=n;j++)
{
if(t-a[i]==t-a[j])
continue;
k++;
a[k]=a[j];
i=j;
}
printf("\n Array after removing the duplicates");
for(i=1;i<=k;i++)
printf(" %d",a[i]);
}``````
``````// this program takes a sorted array as input and prints the unique numbers in that array as the output
// time complexity is of the order n  and also checks whether the array //is sorted or not
#include<stdio.h>

void main(char* argv)
{
int a[100],b[100];
int i=0,j=0,k=0,n=0;
int flag=0;
printf("Enter number of elements in the array \n");
scanf("%d",&n);
printf("Enter all the %d elements \n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
// to check whether if the array is sorted or not
for(i=0;i<n;i++)
if(!(a[i]<=a[i+1]))
flag=1;
if(flag==1)
printf("The given array is not sorted \n");
else
{
for(i=0,j=i+1;j<=n;j++)
{
if(a[i]==a[j])	// we compare if a[i] and a[j] are equal or not if equal then contiue
continue;
b[k++]=a[i];// if they are not equal then b[k++] is equal to the repeating value
i=j;		// assign i==j to start from the end of the repeating elemnet
}
printf("The Unique numbers in the array are \n");
for(i=0;i<k;i++)
printf("%d \n",b[i]);
}
}``````

If you want to have them in the same array insted of b[k++] use a[k++] and print till i<k;