0

I wrote this version of the Merge Sort (this is the part where I merge the parts), but it has a problem. I would like to use it with generics, so I made an array of Object to help me during the process. When I compile, it gives a warning, which I suppressed with that line on the top of the code. Is there a way to avoid using an array of Object? (The method compare is from another class but it work the same as compareTo):

@SuppressWarnings("unchecked")
  public static <T> void merge(ArrayList<T> array, Comparator<T> c, int p, int mid, int q) {
    Object[] tmp = new Object[q-p+1]; 
    int i = p;
    int j = mid+1;
    int k = 0;
    while (i <= mid && j <= q) {
        if (c.compare(array.get(i), array.get(j))<0)
          tmp[k] = array.get(i++);
        else
          tmp[k] = array.get(j++);
        k++;
    }
    if (i <= mid && j > q) {
        while (i <= mid) 
          tmp[k++] = array.get(i++);
    } else {
        while (j <= q)
          tmp[k++] = array.get(j++);
    }
    for (k = 0; k < tmp.length; k++)
      array.set(k+p, (T)tmp[k]);
  }
0x499602D2
  • 87,005
  • 36
  • 149
  • 233
JimBelushi2
  • 275
  • 2
  • 17

2 Answers2

0
public static <T> void merge(ArrayList<T> array, Comparator<T> c, int p, int mid, int q) {
        ArrayList<T> tmp = new ArrayList<T>(q-p+1); 
        int i = p;
        int j = mid+1;
        int k = 0;
        while (i <= mid && j <= q) {
            if (c.compare(array.get(i), array.get(j))<0)

                tmp.add(array.get(i++));
            else
                tmp.add(array.get(j++));
            k++;
        }
        if (i <= mid && j > q) {
            while (i <= mid) 
                tmp.add(array.get(i++));
        } else {
            while (j <= q)
                tmp.add(array.get(j++));
        }
        for (k = 0; k < tmp.size(); k++)
          array.set(k, tmp.get(k));

        System.out.println(array);
      }

You can skip the object array this way. Hope it helps :)

Rajan Singh
  • 189
  • 7
0

Your code is fine. You could also have used:

T[] tmp = (T[]) new Object[q - p + 1];

with same suppression annotation, and skip the cast at (T)tmp[k].

user2023577
  • 1,548
  • 1
  • 10
  • 20