简体   繁体   中英

removing duplicates using insertion sort java

I am having half an issue with the following code, it is an insertion sort method used with the Comparable interface. In this specific case it is supposed to sort elements in decreasing order, which it does fine. However, I am also trying to remove duplicates within the same method but it is not working. I was wondering whether it is actually possible to do that within the same method? I have looked at the answer at the following question Removing Duplicates Inside Insertion Sort but I am not sure how to apply it in here. Not necessarily looking for the solution but if you can point me into the right direction from where I can take it further. Thanks in advance.

public void InsertionSortDecrease(){
    for(int i=1;i<size();i++){
        T keyelement = get(i);
        int pos=i;
        while(pos > 0 && 
(((Comparable)keyelement).compareTo((Comparable)get(pos-1)) > 0)){
            set(pos,get(pos-1));
            pos--;
        }
        set(pos,keyelement);
        if(((Comparable)get(pos)).compareTo((Comparable)get(pos+1)) 
== 0){
            remove(pos);
        }
    }
}

I would personaly use a TreeSet which does what you want.

You can only add an item if it is not already present in the set which is always kept sorted.

You are attempting to remove elements while sorting them. For something like this an Iterator would be a lot better to avoid running into a concurrent modification error.

Your bug is you are counting up , but you should be counting down , because there's no more room to the left of the final result so you should be shuffling to the right as you find the insertion point.

You'll then need to compare for duplicate the current and the previous (if it exists) positions, because you'll already know it's less than the next due to the terminating condition of the first loop. But then you'll have to shuffle them all back if it's a dupe.

Better, first find the insertion point, then if it's a dupe do nothing otherwise shuffle and insert. If you refactor your code in this way, you can then improve the insertion point finder from O(n) to O(log n) by doing a binary search because you know you are operating with sorted data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM