Sunday, July 25, 2010

removing duplicates from an array

With the following java program we can view the array after removing the duplicate elements from an array

public class RemoveDups {
     public static void main(String[] args) {
                int[] dups = new int[] { 0, 0, 0, 0 ,1, 2,2,3,4,5,6,7,2,3,4,5,6};
               removeDups(dups);
   }
   private static void removeDups(int[] dups) {
              int i, j;
              /* new length of modified array */
              int newLength = 1;
             for (i = 1; i < dups.length; i++) {
                   for (j = 0; j < newLength; j++) {
                         if (dups[i] == dups[j])
                              break;
                   }
                   if (j == newLength) {
                       dups[newLength++] = dups[i];
                  }
           }
           for (int y = 0; y < newLength; y++) {
                 System.out.println(dups[y]);
          }
     }
}

No comments: