You are here : Home / Core Java Tutorials / Interview Programs (beginner to advanced) in java / Level1 programs for (beginner)
In this core java programming tutorial we will write a program to Remove duplicate elements from sorted array in java.
Hi! In this post we will be discussing very interesting question - how to remove duplicate elements from find out given out number is binary or not.
Example in java>
Given array = 1 3 7 8 9 14 16 17 16 17 17
output = 1 3 7 8 9 14 16 17
Full Program/SourceCode / Example to Remove duplicate elements from sorted array in java >
/**
* @author AnkitMittal
*
*/
public class RemoveDuplicatesFromSortedArrayExample{
public static void main(String a[]){
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 to Remove duplicate elements from sorted array in java.
/** Copyright (c), AnkitMittal www.JavaMadeSoEasy.com */
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>