-
Notifications
You must be signed in to change notification settings - Fork 0
/
7-DuplicateRemovalFromSortedArray.c
60 lines (56 loc) · 1.99 KB
/
7-DuplicateRemovalFromSortedArray.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
Submitted By: Krishna Kanhaiya
Submitted To: Dr. Aditi Sharan
Course: M.Tech. Data Science (Semester-1)
Subject: Data Structures & Algorithms
Timestamp: January 06, 2023 17.38.05 IST
Help: Julfikaraehmad
Objective: Write an efficient program to delete duplicate elements from a sorted array.
*/
#include<stdio.h>
int print(int sortedArray[], int numberOfElements){
int i;
for(i = 0; i < numberOfElements; i++){
printf("%d\t", sortedArray[i]);
}
printf("\n");
return 0;
}
int removeDuplicates(int sortedArray[], int numberOfElements){
int i, j, lastIndex;
lastIndex = numberOfElements - 1;
//This loop considers last element as a distinct one. So, it starts from 0th element and go upto second last element.
for(i = 0, j = 0; i < lastIndex; i++){
/*
Checks whether two adjacent elements are equal or not.
If they aren't then replace jth element with ith element and place j on next position.
*/
if(sortedArray[i] != sortedArray[i + 1]){
sortedArray[j++] = sortedArray[i];
}
}
/*
j will be on position where last distinct element should be inserted.
Previous loop considered last element as a distinct one, so insert it on jth position.
*/
sortedArray[j] = sortedArray[lastIndex];
//j inserted in lastIndex and then incremented.
lastIndex = j++;
//All positions after lastIndex will be assiged 0.
while(j < numberOfElements){
sortedArray[j++] = 0;
}
//This prints sub-array with distinct elements.
printf("After removal of duplicates:\n");
print(sortedArray, lastIndex + 1);
return 0;
}
int main(){
int sortedArray[] = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5};
printf("Prior removal of duplicates: \n");
print(sortedArray, 15);
removeDuplicates(sortedArray, 15);
//printf("After removal of duplicates:\n");
//print(sortedArray, 15);
return 0;
}