Remove duplicate elements from sorted array in java


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
*/



Previous program                                                                  Next program


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>


>Pattern/Pyramid generating program in java










eEdit
Must read for you :