You are here : Home / Core Java Tutorials / Interview Programs (beginner to advanced) in java / Level2 programs in java (intermediate)
In this core java programming tutorial we will write a program to Remove duplicate elements from sorted array in java.
Hi! we will write a program to remove duplicate elements from sorted array in java.
Example in java>
sorted array(with duplicate elements) : 1 3 7 8 9 14 16 17 16 17 17
sorted array(with non-duplicate elements) : 1 3 7 8 9 14 16 17
Full Program/SourceCode/ Example to Remove duplicate elements from sorted array in java >
/** Copyright (c), AnkitMittal www.JavaMadeSoEasy.com */
public class RemoveDuplicatesFromSortedArrayExample {
public static void main(String args[]){
int[] duplicateSortedAr = {1,3,7,8,8,9,14,16,16,17,17};
int[] nonDuplicateSortedAr = removeDuplicates(duplicateSortedAr);
System.out.print("Displaying contents of sorted array(with duplicate elements) : ");
for(int i=0;i<duplicateSortedAr.length;i++){
System.out.print(duplicateSortedAr[i]+" ");
}
System.out.println();
System.out.print("Displaying contents of sorted array(with non-duplicate elements) : ");
for(int i=0;i<nonDuplicateSortedAr.length;i++){
System.out.print(duplicateSortedAr[i]+" ");
}
}
/**
* This method returns sorted array with non duplicate elements
*/
public static int[] removeDuplicates(int[] duplicateSortedAr){
int i=0, j=1;
if(duplicateSortedAr.length < 2){ //means there is only one element in array.
return duplicateSortedAr;
}
while(j < duplicateSortedAr.length){
if(duplicateSortedAr[j] == duplicateSortedAr[i])
j++;
else
duplicateSortedAr[++i] = duplicateSortedAr[j++];
}
int[] nonDuplicateSortedAr = new int[i+1];
for(int x=0; x<nonDuplicateSortedAr.length; x++){
nonDuplicateSortedAr[x] = duplicateSortedAr[x];
}
return nonDuplicateSortedAr;
}
}
/*OUTPUT
Displaying contents of sorted array(with duplicate elements) : 1 3 7 8 9 14 16 17 16 17 17
Displaying contents of sorted array(with non-duplicate elements) : 1 3 7 8 9 14 16 17
*/
|
So in this core java programming tutorial we wrote a program how to Remove duplicate elements from sorted array in java.
Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.
RELATED LINKS>