Home > JAVA > How to remove duplicate array values in java

How to remove duplicate array values in java

This afternoon one of my friend asked how to eliminate duplicate element on integer array. My solution is simple, first we need to sort the array, second loop the array and copy the different element to new array. The new array will have different element.

First sorting array, I used quicksort algorithm

QuickSort.java

public class QuickSort {
private int[] numbers;
private int number;

public void doSort(int[] values){
if (values ==null || values.length==0){
return;
}
this.numbers = values;
number = values.length;
doQuickSort(0, number - 1);
}

private void doQuickSort(int low, int high){
int i=low, j=high;
int pivot = numbers[low + (high-low)/2];

while(i<=j){
while(numbers[i] < pivot){
i++;
}
while(numbers[j] > pivot){
j--;
}
if(i <=j){
exchange(i, j);
i++;
j--;
}
}

// Recursion
if (low < j)
doQuickSort(low, j);
if (i < high)
doQuickSort(i, high);
}

private void exchange(int i, int j) {
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}

Second, loop through array and copy element that does not have duplicate.

RemoveDuplicateArray.java

public class RemoveDuplicateArray {
private int[] newArray;

public int[] doRemoveDuplicateArray(int[] oldArray){
newArray = new int[oldArray.length];
int pivot = oldArray[0];
newArray[0] = pivot;
for(int i=1, k=1; i<=oldArray.length-1; i++){
if(oldArray[i] != pivot){
pivot = oldArray[i];
newArray[k] = pivot;
k++;
}
}
return newArray;
}
}

Tes the code

public class TestRemoveDuplicateArray {

public static void main(String[] args) {
int[] test = { 5, 5, 6, 6, 4, 4, 5, 5, 4, 4, 6, 6, 5, 5 };
System.out.println("The array " + Arrays.toString(test));
new QuickSort().doSort(test);
System.out.println("The array after short " + Arrays.toString(test));
System.out.println("The array after remove duplicate " +
Arrays.toString(new RemoveDuplicateArray().doRemoveDuplicateArray(test)));
}

}

The output

output

As you can see the new array have zero (0) value. This is because I define the length of new array same as the old one. Therefore default value is used to fill the element that not been filled.

Categories: JAVA
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: