Implementing Merge sort algorithm ran on threads

Viewed 18

So i am writing a program where multiple sort algorithms will be running simultaneously as threads. I have successfully ran other sorting algorithm in threads. But when writing the merge sort class, the run2 method gives me a "non-static type variable T cannot be referenced from a static context" error. How can I get around this problem?

public class mergeSort<T extends Comparable<? super T>> implements Runnable {

    private  final List<T> m_list;
    private final int m_low, m_high;

    public mergeSort(List<T> list, int low, int high) {
        m_list = list;
        m_low = low;
        m_high = high;
    }

    // MERGE SORT 
    private static <T extends Comparable<T>> void merge(List<T> list, int low, int mid, int high) {
        // find sizes of two subarrays to be merged
        int n1 = mid - low + 1;
        int n2 = high - mid;
        // create temp arrays
        List<T> left = new ArrayList<>();
        List<T> right = new ArrayList<>();
        // copy data to temp arrays
        for (int i = 0; i < n1; i++) {
            left.add(list.get(low + i));
        }
        for (int j = 0; j < n2; j++) {
            right.add(list.get(mid + 1 + j));
        }
        // merge the temp arrays
        // initial indexes of first and second subarrays
        int i = 0, j = 0;
        // initial index of merged subarray array
        int k = low;
        while (i < n1 && j < n2) {
            if (left.get(i).compareTo(right.get(j)) <= 0) {
                list.set(k, left.get(i));
                i++;
            } else {
                list.set(k, right.get(j));
                j++;
            }
            k++;
        }
        // copy remaining elements of left if any
        while (i < n1) {
            list.set(k, left.get(i));
            i++;
            k++;
        }
        // copy remaining elements of right if any
        while (j < n2) {
            list.set(k, right.get(j));
            j++;
            k++;
        }
    }

    private static void run2(List<T> list, int low, int high) {
        //This previously was the body of your `run()` function.
        if (low < high) {
            int mid = low + (high - low) / 2;
            run2(list, low, mid - 1);
            run2(list, mid + 1, high);
            merge(list, low, mid, high);
        }
    }

    @Override
    public void run() {
        run2(m_list, m_low, m_high);
    }

}
0 Answers
Related