Menu

Remove redundant elements in a sorted array

Java forum
Duy Dinh
2012-03-08
2013-06-13
  • Duy Dinh

    Duy Dinh - 2012-03-08
     /**
     * Extract unique elements from an array
     * 
     * @param arr input array with redundant elements
     */
    public static void removeRedundantElements(ArrayList arr) {
        Collections.sort(arr);
        // remove the same elements
        for (int k = 0; k < arr.size() - 1; k++) {
            Object e = arr.get(k);
    
            // try to skip same element
            int j = k + 1;
            while (j < arr.size()) {
                if (arr.get(j).equals(e)) {
                    arr.remove(j);
                    j--;
                }
                j++;
            }
        }
    }
    
     

    Last edit: Duy Dinh 2013-06-13
  • Duy Dinh

    Duy Dinh - 2013-06-13

    A better way to get unique elements from an array

    // temporary array of the same size
        int[] b = new int[a.size()];
        Collections.sort(a);
    
        // store the first element
        b[0] = a.get(0);
        int bIndex = 1;
        // browse 'a' and collect unique elements into b
        // the element collected must not equal to the previous element
        for (int aIndex = 1; aIndex < a.size(); aIndex++) {
            if (b[bIndex - 1] != a.get(aIndex)) {
                b[bIndex] = a.get(aIndex);
                bIndex++;
            }
        }
    
        // copy elements in temporary elements from index 0 to bIndex 
        int[] result = Arrays.copyOfRange(b, 0, bIndex);
    
        return result;
    
     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.